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

StackOverflow https://stackoverflow.com/questions/10546137

  •  07-06-2021
  •  | 
  •  

Question

“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();
    }
}
Was it helpful?

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.

OTHER TIPS

private means access only through class scope. It wouldn't be logical suddenly this rule will not apply for nested class.

I don't define any other type of nested class except of private. And their members that I want to be accessed from the parent class I made them to be public.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top