Skip to content
Advertisement

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,

JavaScript

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?

Advertisement

Answer

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.

JavaScript

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

JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement