In "Cracking the Coding Interview" by J. Laakmann McDowell, I found an interesting question concerning the influence of private constructors on inheritance in Java. I know that this is not forbidden in Java, so I'm wondering in which cases it might be useful.
In Java, it is not possible to inherit a class with a private constructor. But if this class is internal, the parent class can access all private methods of internal classes. Thus, the inheritance of internal classes with private constructors is possible in the scope of the parent class. I think this is useful for implementing Singletons.
I want to demonstrate these cases in the following example:
In Java, it is not possible to inherit a class with a private constructor. But if this class is internal, the parent class can access all private methods of internal classes. Thus, the inheritance of internal classes with private constructors is possible in the scope of the parent class. I think this is useful for implementing Singletons.
I want to demonstrate these cases in the following example:
import java.util.*;
import test.*;
public class Main {
class PrivateClassA {
private PrivateClassA() {
System.out.println("Private constructorA");
}
}
/* PrivateClassB inherits the class with the private constructor */
class PrivateClassB extends PrivateClassA {
public PrivateClassB() {
super();
System.out.println("Private constructorB");
}
}
public static void main(String[] args) {
Main main = new Main();
PrivateClassB bInstance = main.new PrivateClassB();
PrivateClassD dInstance = new PrivateClassD();
}
}
package test;
import java.util.*;
public class PrivateClassC {
private PrivateClassC() {
System.out.println("Init class C");
}
}
package test;
import java.util.*;
// PrivateClassC cannot be inherited because this class has a private constructor
public class PrivateClassD /* extends PrivateClassC */{
public PrivateClassD() {
// The Inheritance of private constructor causes an exception
// super();
System.out.println("Init class D");
}
}
Comments
Post a Comment