Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {}
    }
}
like image 394
Đinh Carabus Avatar asked Jul 31 '13 17:07

Đinh Carabus


People also ask

Should a class constructor be public or private?

There is no rule that constructor to be public . Generally we define it public just because we would like to instantiate it from other classes too . Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.

Can a private class have public constructor?

The private class can't be extended by classes outside of the package, so protected has no use either. Even when using reflections, a public constructor is not accessible by default from other packages and will throw a IllegalAccessException . It checks the class visibility first, then the member visibility.

Can we declare inner class as private?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it.

Can private class have public constructor in Java?

Modifiers public, protected and, private are allowed with constructors. We can use a private constructor in a Java while creating a singleton class. The Singleton's purpose is to control object creation, limiting the number of objects to only one.


2 Answers

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.

like image 59
Peter Lawrey Avatar answered Nov 15 '22 16:11

Peter Lawrey


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.

like image 40
elefont Avatar answered Nov 15 '22 18:11

elefont