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.
public − This is the access specifier that states that the method can be accesses publically. static − Here, the object is not required to access static members. void − This states that the method doesn't return any value.
Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you).
Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong.
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.
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.
(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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With