Way2Java

Private variable Accessibility Java Private access specifier

Private access specifier and Private variable requires more elaborate discussion as many people are not aware of its in and outs.

private variables and methods of a class can be accessed within the same class only. By inheritance, even subclasses cannot use by composition. Maximum extent other classes should call through the public methods of the same class as in the following program.

class Test
{
    private int x = 10;                 // observe private variable
    public void display()
    {
         System.out.println(x);
    }
}
public class Demo extends Test
{
    public static void main(String args[])
    {
         Demo d1 = new Demo();
         // System.out.println(d1.x);   // error  (inheritance)

          Test t1 = new Test();
          //  System.out.println(t1.x); // error  (composition)

          t1.display();   // works nice
    }
}

In the above code, the subclass object d1 of Demo class cannot call the private variable x of the super class Test. That is, x can be accessed by Test object only in Test class itself.

public void display()
{
System.out.println(x);
}

Other classes like Demo, can call x private variable of Test class with public method display() of Test class.

Calling private variables from public methods is one the coding styles Developers adopt and it got a very good advantage and more discussed in Public methods and Private Variables.