How to prevent the outer class method from accessing privately defined methods or fields of a nested class?



I am attempting to prevent the OuterMethod from accessing the privately-defined field InnerField and method InnerMethod. It does not seem to work as what I expect.

import static java.lang.System.out;

class Outer {

    void OuterMethod() {
        Inner.InnerMethod();
        out.println(new Inner().InnerField);
    }

    private final static class Inner {
        private final int InnerField = 20;

        private static void InnerMethod() {
            out.println("Inner Method");
        }
    }
}

public class Test {

    public static void main(String[] args) {
        new Outer().OuterMethod();
    }
}

Question

How to prevent the outer class method from accessing privately defined methods or fields of a nested class?

Answer

You can’t. Java says so.

From the Java Language Specification, section 6.6.1, Determining Accessibility:

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.

And, really, it would not make a lot of sense to restrict access. The outer class programmer is in full control of the inner class; he can exercise restraint if he so chooses.

Otherwise, promote the inner class to the top level.



Source: stackoverflow