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.

2 thoughts on “Private variable Accessibility Java Private access specifier”

  1. hello Sir..

    I have a doubt that if i can access private data members from outside the class through methods and constructor.

    so how can we say that private data members scope is only within the class…??? i’m very confused…

    1. Private means, the members of the class can use. That is, you are accessing through the members of the same class only. Suppose imagine, I got property which is private to me. Here, to me means not that I can use alone, whole family members can use. You can use my property though my son but you cannot access directly. This is the meaning of private, understand.

Leave a Comment

Your email address will not be published.