Private variable Accessibility Java Private access specifier

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.

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()

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. Nikunj Jani

    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. S. Nageswara Rao, Corporate Trainer Post author

      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 Reply

Your email address will not be published. Required fields are marked *