Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor and inheritance (Java)

Tags:

java

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?

like image 271
Eugene Avatar asked Sep 19 '25 03:09

Eugene


2 Answers

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;
    }    
}
like image 51
Jon Skeet Avatar answered Sep 20 '25 16:09

Jon Skeet


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();
    }
}
like image 44
jmj Avatar answered Sep 20 '25 18:09

jmj