I have a java class.
Class ClassA {
ClassA(int type)
{
switch(type)
{
case 1: handleType1(); break;
case 2: handleType2(); break;
default: throw new IllegalArgumentException(); break;
}
}
private void handleType1(){}
private void handleType2(){}
}
Now I have to add support for type 3 and type 4. But I can not modify code of ClassA.
So I thought I would write ClassB which extends ClassA and add support for type3 and type 4 as below.
Class ClassB extends ClassA{
ClassB(int type)
{
case 3: handleType3(); break;
case 4: handleType4(); break;
default:
{
try{
/* To support type 1 and type 2. */
super(type);
} catch(IllegalArgumentException e) {
/* Handle exception. */
}
} break;
}
private void handleType3(){}
private void handleType4(){}
}
I thought this would work. But I got "Call to super() must be first statement in constructor body" error in ClassB's construcor.
I read this post and I understand why super() has to be the first statement in the constructor.
I can address my use-case by writing complete code of ClassA in ClassB and adding support for type 3 and 4. But I want to know if there are any better solutions to this problem.