0

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)
    }
}
Mazmart
  • 2,703
  • 4
  • 17
  • 20

2 Answers2

2

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);
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Rather than using two constructors, use single constructor and use if ( a instanceOf B) and cast the object in B to perform all the operations related to class B specifically. like below snippet

Class C {
    C(A a){
        if(a instanceOf B){
            B b =(B) a;
            // all the stuff related to B only
        }
        //common work for both the scenarios
    }
}
Georgios Syngouroglou
  • 18,813
  • 9
  • 90
  • 92
VijayD
  • 826
  • 1
  • 11
  • 33
  • I've mentioned that instanceOf is not an option as Class C is not in the same package and can be distributed alone so a ClassNotFound would be fired. – Mazmart Apr 08 '16 at 10:48
  • CNF will be fired in any case then, if the class is not accessible, what instanceOf has to do with it.? `For ClassNotFoundException: Thrown when an application tries to load in a class through its string name using: 1. The forName method in class Class. 2. The findSystemClass method in class ClassLoader. 3. The loadClass method in class ClassLoader.` – VijayD Apr 11 '16 at 12:02