Can Java Constructor build a subclass object?

Is there a way to change the class that is being built in the constructor?

public class A {
  A() {
    //if (condition) return object of type B
    //else return A itself
  }
}
public class B extends A { }

Basically, I want to use the base class constructor as a factory method. Is this possible in java?

+3
source share
5 answers

No, you have to use the factory method for Aif you want to do this. The client of your class has the right to expect that if it executes new A(), it will receive a class object A, and no other.

+9
source

No, constructors only need to instantiate the class object that they represent. This is why there is no return value in the constructor.

+5
source

, :

public class A {

private A(){ }

public static A getInstance(){
     if (condition) 
        return new B();
     else 
        return new A();
}

}

class B extends A {

}
+2

When the constructor code is called, the object is already created - you only initialize its fields. So it's too late to modify the class of an object.

+2
source

You can try using reflection to create a subclass. However, this is a bad idea because the class does not need to know about its subclasses.

Using the factory method is the best approach in your case.

+1
source

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


All Articles