Home > Net >  Is it possible to access a private static variable and method?
Is it possible to access a private static variable and method?

Time:10-03

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?

CodePudding user response:

The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.

private static int a = 5;

public static int getA () {
    return a;
}

You can then statically call this method and retrieve the private static field.

// ...
System.out.println(A.getA());

Usually private static fields are rarely used though.

One more thing I'd like to add is the general use of static here. As you actually create an instance of the class A the static modifier is redundant.

  • Related