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

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

问题描述

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 的含义 - 您几乎肯定希望这些变量是静态变量,因为它们适用于 each Employee 而不是一般的 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天全站免登陆