0

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?

DEV_BOT
  • 33
  • 9
  • 1
    Only through a getter method. `private` means you won't be able to access it from outside. – 0xff Oct 03 '21 at 06:38

2 Answers2

3

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.

0xff
  • 181
  • 2
  • 11
0

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.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '22 at 02:46