javaoopinheritance

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 http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html


Solution

  • 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();
            in.seeOuter();
        }
        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();
            inner.seeOuter();
        }
    }
    

    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