Suppose we have the following code:
class Test {
private Test() {
System.out.println("test");
}
}
public class One extends Test {
One() {
System.out.println("One");
}
public static void main(String args[]) {
new One();
}
}
When we create an object One, that was originally called the parent class constructor Test(). but as Test() was private – we get an error.
How much is a good example and a way out of this situation?
There is no way out. You have to create an available (
protected,publicor default) super constructor to be able to extendtest.This kind of notation is usually used in utility classes or singletons, where you don’t want the user to create himself an instance of your class, either by extending it and instanciating the subclass, or by simply calling a constructor of your class.
When you have a
classwith onlyprivateconstructors, you can also change theclasstofinalbecause it can’t be extended at all.Another solution would be having a method in
testwhich create instances oftestand delegate every method call fromOneto atestinstance. This way you don’t have to extendtest.