Đinh Carabus
Đinh Carabus

Reputation: 3496

Should the constructor of a private inner class be declared public or private?

Is there any actual difference between this

public class OuterClass {
    private class InnerClass {
        public InnerClass() {}
    }
}

and this?

public class OuterClass {
    private class InnerClass {
        private InnerClass() {}
    }
}

Upvotes: 12

Views: 1315

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Accessing private members from another class is slightly more complicated because the JVM doesn't actually allow this. As a result the compiler injects accessor methods which makes it slightly slower or your stack trace more complicated.

For these reason I leave it as package local.

BTW The constructor of an abstract class doesn't need to be public either. It may as well be protected or package local

private static class A {
    private A() {
        throw new Error();
    }
}
public static void main(String... ignored) {
    new A();
}

prints an extra stack trace element.

Exception in thread "main" java.lang.Error
    at Main$A.<init>(Main.java:8)
    at Main$A.<init>(Main.java:6)
    at Main.main(Main.java:12)

Make the constructor package local and the second one disappears.

Upvotes: 10

elefont
elefont

Reputation: 151

As far as other classes are concerned, it shouldn't since the inner class is declared as private. They can't see it at all.

It shouldn't make a difference to the enclosing class since it contains the inner class.

Upvotes: 9

Related Questions