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?
Well, it certainly can! That doesn't mean it should. Java allows it as extension so it's a nice feature when properly used.
The answer is you can't extend the Parent class if it has a private default constructor. You have to make the constructor available to the subclass. In this case you need to have a default constructor that have a protected or public or default access modifier.
Java doesn't prevent sub-classing of class with private constructors. What it prevents is sub-classes which cannot access any constructors of its super class. This means a private constructor cannot be used in another class file, and a package local constructor cannot be used in another package.
A class that extends another class does not inherit its constructors. However, the subclass must call a constructor in the superclass inside of its the subclass constructors! If a subclass calls another constructor within itself, then the called constructor must call the superclass constructor.
There is no way out. You have to create an available (protected
, public
or default) super constructor to be able to extend test
.
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 class
with only private
constructors, you can also change the class
to final
because it can't be extended at all.
Another solution would be having a method in test
which create instances of test
and delegate every method call from One
to a test
instance. This way you don't have to extend test
.
class Test { private Test() { System.out.println("test"); } public static Test getInstance(){ return new Test(); } public void methodA(){ //Some kind of implementation } } public class One { private final Test test; One() { System.out.println("One"); test = Test.getInstance(); } public void methodA(){ test.methodA(); } public static void main(String args[]) { new One(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With