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?
-
No, you can't do this.
-
No, constructors will only allow a return value of the class they represent. That is why there is no return value specified in the constructor.
Steve Kuo : Constructors don't return values -
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 he doesnew A()
, he gets an object of classA
, and no other.: well, this is possible in some other languages. when user does new A() he can as well get subtype of A. So conceptually I see no issue.Pavel Minaev : Nonetheless, it is the expectation in Java. -
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.
-
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 { }
-
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.
0 comments:
Post a Comment