Private constructor and inheritance (Java)

I have a first class for which the constructor takes a parameter.

public class First {
    First(Object o){
        o.toString();
    }
}

I have a second class that extends this first one.

public class Second extends First {
    Second(Object o) {
        super(o);
    }
}

I want to keep the constructor of the Secondprivate class in order to be able to create an instance of only one instance of this class (for example, using the Singleton template), but the compiler does not allow me to do this.

If I cannot set the constructor as private here, what can I do to allow only one instance of the class to be created?

+3
source share
3 answers

Second private . , , First private, .

:

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;
    }    
}
+8

!!

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();
    }
}
+2
public class Second extends First{
    private static final Second instance = new Second(new Object());
    private Second(Object o) {
    super(o);
    }
    public static Second instance(){
    return instance;
    }
}
0
source

Source: https://habr.com/ru/post/1781227/


All Articles