"private" access specifier 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 other classes should call through the public methods of the same class as in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Test { private int x = 10; 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.
Demo can use Test class object to call display() method to print x value.
You can know more about private variables in Public methods and Private Variables.
If you have any Questions, please ask below