Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

java - Difference between public static and private static variables

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);
}
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • A public variable is accessible from anywhere (well, anywhere where the class is accessible).

  • A private variable is only accessible inside the class.

  • A static variable belongs to the class rather than to an instance of a class.

  • Notice that the variable DEPARTMENT is also final, which means that it cannot be modified once it is set. This is important here because that's what saves this from being bad code -- the variable is a constant so it's okay to give things outside the class access to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...