Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java Constructor construct an object of a subclass?

Tags:

java

factory

Is there a way to modify the class being constructed in a 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 it possible in java?

like image 366
amit Avatar asked Nov 30 '22 06:11

amit


1 Answers

No, you'll have to use a factory method for A if you want to do this. The client of your class has a right to expect that, if they do new A(), they get an object of class A, and no other.

like image 58
Pavel Minaev Avatar answered Dec 05 '22 08:12

Pavel Minaev