I need my Class C to choose correct constructor based on instance variable. I have basic code shown below. Whenever I create instance of an class B and store it as reference to A. 'Wrong' constructor is used on class C. What are my options to change this if I don't want to use (b instanceOf B) because it is in other package.
Class A {
}
Class B extends A {
}
Class C {
C(A a){...}
C(B b){...}
}
Class Main{
private createClass(String s){
if (...){
return new B();
}
}
public static void main(String[] args){
A b = createClass("s");
new C(b); //--> constructor C(A a) is used but i need C(B b)
}
}
new C(A a)
is called, because the b
variable is of type A
at compile-time. The compiler doesn't know that at Runtime it will hold reference to an instance of B
and that's why it binds to the new C(A a)
constructor.
In general, I think your should reconsider your design, but if you want to keep it like this, you could at least make the createClass()
method Generic and pass the Class<T>
of the resuling type:
private <T extends A> T createClass(String s, Class<T> clazz){
if (...) {
return clazz.newInstance();
}
//
}
This will allow you to point out (and easily switch) the type of the result you need:
B b = createClass("s", B.class);
new C(b);