公共静态和私有静态变量之间的区别 [英] Difference between public static and private static variables

查看:921
本文介绍了公共静态和私有静态变量之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Employee{
 // salary  variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
 public static final String DEPARTMENT = "Development";

public static void main(String args[]){
   salary = 1000;
  System.out.println(DEPARTMENT+  "  average salary:"+salary);
}
}

这个java程序包含一个静态变量。但是我无法理解公共和私有静态变量之间的区别。

This java program contains a static variable. But I cannot understand the difference between public and private static variables.

推荐答案

公共变量可以在任何地方访问在代码中 - 私有变量只能在类本身中访问。在这种情况下,你在 Employee 类中使用 Employee.salary ,所以没关系。

A public variable is accessible everywhere in the code - a private variable is only accessible within the class itself. In this case you're using Employee.salary within the Employee class, so that's fine.

请注意,变量是静态的是一个完全独立的问题 - 方法和类的可访问性与变量相同。

Note that the variable being static is a completely separate matter - and methods and classes have accessibility in the same way as variables.

还有其他级别的访问权限 - protected 和默认的包访问权限(无法明确指定)。请参阅 Java语言规范的第6.6节有关详细信息

There are other levels of access available too - protected and the default "package" access (which can't be specified explicitly). See section 6.6 of the Java Language Specification for more details.

(另外一点,也值得了解 static 的含义 - 你几乎肯定希望这些变量是静态的,因为它们适用于每个 Employee 而不是一般来说,员工概念。 DEPARTMENT 在这里也是一个常数很奇怪。)

(As a side matter, it's also worth learning about what static means - you almost certainly don't want these variables to be statics, as they apply to each Employee rather than the Employee concept in general. It's odd for DEPARTMENT to be a constant here, too.)

这篇关于公共静态和私有静态变量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆