I have first class for which constructor takes a parameter.
public class First {
First(Object o){
o.toString();
}
}
I have a second class which extends this first one.
public class Second extends First {
Second(Object o) {
super(o);
}
}
What I want is to keep the constructor of Second
class private in order to have a possibility to instantiate the only one instance of this class (using Singleton pattern, for instance), but compiler doesn't allow me to do that.
If I can't set the constructor as private here, what can I do to allow the only one instance of the class to be created?
You can make the constructor of Second
private with no problems. What you can't do is make the constructor of First
private, unless you use nested classes.
As an example, this works fine:
class First {
First(Object o) {
o.toString();
}
}
class Second extends First {
private final static Second instance = new Second(new Object());
private Second(Object o) {
super(o);
}
public static Second getInstance() {
return instance;
}
}
Here it is working !!
class First {
First(Object o){
o.toString();
}
public First() {//I think you missed this
}
}
class Second extends First {
private static Second obj ;
private Second(Object o) {
super(o);
}
private Second() {
}
public static Second getInstance(){
if(obj == null){
obj = new Second(new Object());
}
return obj;
}
}
public class SingleTon {
public static void main(String[] args) {
Second sObj = Second.getInstance();
}
}
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