"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.
private int x = 10;
public void display()
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.
================Would you like to dig more into?=================
1. Java Private variable accessibility (Private access specifier)
2. What is Java private and private variable?
3. What is Java private method?
4. What is Java protected and protected method?
5. Can you override private method with Example?
6. Can we override protected method?
7. Access Specifiers & Access Modifiers