Reputation: 10892
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?
Upvotes: 4
Views: 1803
Reputation: 101605
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.
Upvotes: 9
Reputation: 39495
No, constructors will only to instantiate an object of the class they represent. That is why there is no return value specified in the constructor.
Upvotes: 5
Reputation: 12413
When constructor code is being invoked the object is already created - you are only initializing its fields. So it's too late to modify class of the object.
Upvotes: 3
Reputation: 5335
You cannot do it in a constructor but you could do:
public class A {
private A(){ }
public static A getInstance(){
if (condition)
return new B();
else
return new A();
}
}
class B extends A {
}
Upvotes: 4
Reputation: 2505
You could try using reflection to instantiate the subclass. However it is a bad idea because a class shouldn't know about its subclasses.
Using a factory method is the best approach in your case.
Upvotes: 1