Private field in subclass is accessible in superclass

It is written in JLS (see section 8.3):

"A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass."

Could you give an axample of this statement?

I know that we can write:

public class MyClass {
    private int x = 1;

    public void testExample(MyClass m) {
        m.x = 2;
    }
}

Here we access private field m.x but we do not have "Super Class" - "Sub Class" here.

Jon Skeet
people
quotationmark

It's talking about nested classes - here's an example:

public class Test {
    public static void main(String[] args) {
        new Subclass(10).foo();
    }

    static class Superclass {
        private int x;

        Superclass(int x) {
            this.x = x;
        }
    }

    static class Subclass extends Superclass {
        Subclass(int x) {
            super(x);
        }

        public void foo() {
            Superclass y = this;
            System.out.println(y.x);
        }
    }
}

It's valid because of JLS 6.6:

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (ยง7.6) that encloses the declaration of the member or constructor

Here the use of x is within the body of Test, which is the top level class enclosing the declaration of x... although if you try to use x unqualified, or just this.x, that fails... precisely because x isn't actually inherited (as per the piece of spec you quoted).

people

See more on this question at Stackoverflow