Search code examples
javaprivateinner-classesfinaloverriding

inner class have access to private final methods in base class but why?


Why creators of java allowed this situation? I am sure there must be some reason for it. My below code allows Lion to mischievously run as fast as Cheetah.

public class animal {
    class carnivores {
       private final void runAsFastAsCheetah() {
           System.out.println("Ran as fast as Cheetah");
        }
    }
    public class Lion extends carnivores {
       public void runAsFastAsLion() {
           System.out.println("Ran as fast as Lion.");
           super.runAsFastAsCheetah();
        }
    }
    public static void main(String[] args) {
        animal animal = new animal();
        Lion lion = animal.new Lion();
        //lion.runAsFastAsCheetah(); //Not allowed but//
        lion.runAsFastAsLion();
    }
}

EDIT: For those taking Lion and cheetah seriously, I have modified code.

public class foo {
    class A {
        private final void myMethod() {
            System.out.println("in private final myMethod()");
        }
    }
    public class B extends A {
        public void myMethod() {
            System.out.println("in B's myMethod()");
            super.myMethod();
        }
    }
    public static void main(String[] args) {
        foo foo = new foo();
        B b = foo.new B();
        b.myMethod();
    }
}

Solution

  • All classes with the same outer class can access private members of any other class of the same outer. This features was added when nested classes were added. IMHO this was because these members are compiled together and it makes nested classes more useful.

    Note: The JVM doesn't support this feature, and thus the compiler add accessor methods which appear the the stack traces like access$100. These are added by the compiler to allow access to private members between classes.


    Access modifiers only check one level. If A can access B and B and access C, then A can access anything B lets it access which could be C.

    The reason this is don't is to avoid making private meaningless. If a private member could only be accessed by class which could access it, it would mean it could only be called by a main in the same class. This would make it useless in any other class.