Consider the following code:
public abstract class Base {
public void getAnswer();
}
public class Derived1 extends Base {
public void getAnswer() {
}
}
public class Derived2 extends Base {
public void getAnswer() {
}
}
public class Main {
public final int DERIVED1 = 1;
public final int DERIVED2 = 2;
public Base b;
public static void Main() {
int which_obj = which();
switch (which_obj) {
case DERIVED1: Derived1 derived1 = new Derived1();
// construct object
b = derived1;
break;
case DERIVED2: Derived1 derived1 = new Derived1();
// construct object
b = derived2;
break;
}
b.getAnswer();
}
}
here we are using a switch case to decide what object to construct and accordingly we construct it and assign it to b so as to use polymorphism.
what advantage is polymorphism giving us here?
Now is there a method by which we can avoid the switch case. say: there is a mapping from int to String that returns "Derived1" or "Derived2". given the string containing the name of the class. now can i construct an object given the String containing the name of the class. something like:
Base b = construct_obj(str);
the library call construct_obj automatically locates the class of obj from the bytecodes and returns a reference to the object. then i can avoid the switch case. typically i would be having 100's of Derived classes.