We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?
The
privatekeyword means that it'll only be visible within the class. So in your example it means that you cannot access it likeA.a. What you can do though is to create apublicmethod that returnsa.You can then statically call this method and retrieve the
private staticfield.Usually
private staticfields are rarely used though.One more thing I'd like to add is the general use of
statichere. As you actually create an instance of the classAthestaticmodifier is redundant.