Member Class access modifier

93 Views Asked by At

its obvious that the Default access modifier for the normal class is package private and it's private for the inner Local class or the inner anonymous but what is not obvious to me that Member class it like a private member when we trying to see it from outside the container class so is it private or package private?

2

There are 2 best solutions below

0
On BEST ANSWER

Like Tim B stated everything by default is package private, except for in interfaces.

The following code segment demonstrates this.

public class OuterClass {

    @Override
    public String toString() {
        return "I am the public outer class";
    }

    static class StaticInnerClass {
        @Override
        public String toString() {
            return "I am the package private inner class";
        }
    }

    class NonStaticInnerClass {
        @Override
        public String toString() {
            return "I am the package private non static inner class";
        }
    }

    public static void main(String[] args) {
        OuterClass oc = new OuterClass();
        OuterClass.StaticInnerClass ic = new OuterClass.StaticInnerClass();
        NonStaticInnerClass nsic = oc.new NonStaticInnerClass();
        System.out.println(oc);
        System.out.println(ic);
        System.out.println(nsic);
        System.out.println(new SecondClass());
    }
}

class SecondClass {
    @Override
    public String toString() {
        OuterClass oc = new OuterClass();
        OuterClass.StaticInnerClass ic = new OuterClass.StaticInnerClass();
        OuterClass.NonStaticInnerClass nsic = oc.new NonStaticInnerClass();
        return oc.toString() + "\n" + ic.toString() + "\n" + nsic.toString();
    }
}
2
On

Everything has default access (which is package private) unless you specify otherwise.

(Except in interfaces where everything is public by default)