Search code examples
javainner-classesmodifier

“public” or “protected” methods does not make any difference for a private nested class which does not implement any interface ..?


“public” or “protected” methods does not make any difference for a private nested class which does not implement any interface ..?

If a private nested class does not implement any interface or inherit from any class, for the modifiers of its methods , it seems “public” or “protected” or no modifier do not make any difference. It would make more sense if the compiler allows “private” only for them. So why does java allow them?

class Enclosing {

    private class Inner {
        private void f1() {}
        void f2() {}
        protected void f3() {}
        public void f4() {}
    }

    void test() {
        Inner o= new Inner();
        o.f1();
        o.f2();
        o.f3();
        o.f4();
    }
}

Solution

  • Here is what I just tried:

    public class Test {
    
        public void method(){
    
            Innerclass ic = new Innerclass();
            InnerClass2 ic2 = new InnerClass2();
            System.out.println(ic.i);
            System.out.println(ic.j);
            System.out.println(ic.k);
            System.out.println(ic.l);
    
            System.out.println(ic2.i);  // Compile Error
            System.out.println(ic2.j);
            System.out.println(ic2.k);
            System.out.println(ic2.l);
        }
    
        private class Innerclass{
    
            private int i;
            public int j;
            protected int k;
            int l;
    
        };
    
        private class InnerClass2 extends Innerclass{
    
        }
    
    }
    

    This has one error as mentioned above.

    1. Even if the inner class is private, all the members of inner class are accessible to enclosing/outer class irrespective of their visibility/access modifier.
    2. But the access modifiers does matter if one inner class is extending another inner class.
    3. These are the general inheritance rule applied to any to classes related by inheritance.
    4. Hence java allows all access modifiers in the private inner class.