Ali Ismayilov Ali Ismayilov - 1 year ago 114
Java Question

Access to Private Members of a Superclass

What is the example of indirect access to private member of superclass from subclass?

A nested class has access to all the private members of its enclosing
class—both fields and methods. Therefore, a public or protected nested
class inherited by a subclass has indirect access to all of the
private members of the superclass.

Quote from

Answer Source

In the quote, we talk about "nested" class

here is an example of how an inner class can access private fields of the outer class.

class OuterClass {
private int x = 7;

public void makeInner(){
    InnerClass in = new InnerClass();
class InnerClass {
    public void seeOuter() {
        System.out.println("Outer x is " + x);
public static void main(String[] args) {
    OuterClass.InnerClass inner = new OuterClass().new InnerClass();


Finally, if you extend a class with the InnerClass, they will also access the private fields of the OuterClass if your InnerClass is public or protected