Fresher Fresher - 4 months ago 10
Java Question

Why use access specifiers when defining inner (non-static nested) classes in Java?

Consider the following snippet:

class Deep {

static class StaticInner {

}

class InnerClass {

}

public class InnerClass2 {

}

private class InnerClass3 {

}

protected class InnerClass4 {

}
}

public class Test {

public static void main(String args[]) {
Deep.StaticInner sc = new Deep.StaticInner(); // valid
Deep.InnerClass ic = new Deep.InnerClass(); // invalid
Deep.InnerClass2 ic2 = new Deep.InnerClass2(); // invlaid
Deep.InnerClass3 ic3 = new Deep.InnerClass3(); // invalid
Deep.InnerClass4 ic4 = new Deep.InnerClass4(); // invalid
}
}


Except the static class inside Deep named
StaticInner
, all other nested classes require the enclosing class
Deep
, to be accessed. In other words, they can't be accessed outside of
Deep
(that's my understanding). I have seen programmers specifying the specifiers before nested-inner classes. What's the point? If (non-static) inner classes are not at all accessible outside of the enclosing class, why specifiers (
public
,
private
, &
protected
) are given? Why Java even supports access specifiers on inner classes?

Answer

You can instantiate public non static inner class like this:

public class HelloWorld{

    public class HellowWorld2{
        public HellowWorld2(){
            System.out.println("Hellow World2");
        }
    }

     public static void main(String []args){
        System.out.println("Hello World");
        new HelloWorld().new HellowWorld2(); //The instantiation
     }
}

If hellowworld2 was private you could not have done it. So its not totally pointless, you might have some scenario where you want to instantiate outside the outer class and dont care about the outer class reference.

Comments