DEV_BOT
DEV_BOT

Reputation: 51

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

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?

Upvotes: 1

Views: 1898

Answers (2)

naveen anand967
naveen anand967

Reputation: 1

You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

Upvotes: 0

0xff
0xff

Reputation: 189

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.

Upvotes: 3

Related Questions