0

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.

Community
  • 1
  • 1
MayurK
  • 1,925
  • 14
  • 27

3 Answers3

0

Now I have to add support for type 3 and type 4. But I can not modify code of ClassA.

Then ClassB cannot reasonably subclass ClassA. A subclass must call a parent class constructor. (The unreasonable way it might subclass it would be to lie to the ClassA constructor by passing in a different type.)

Ideally, ClassA and ClassB would both implement an interface, and the rest of the application would be coded to use that interface rather than ClassA or ClassB specifically.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Parent class must be correctly initialized (via explicitly or implicitly calling parent class constructor) during initializing a child class, but in your case parent class can't be initialized with types 3 and 4 (and without types too).

Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
0

You have a serious design flaw.

switches in general are a strong sign that you should make use of interfaces and polymorphism.

The code you currently have in the constructor of A should be in a factory class, and there should be an implementation of an interface declaring common methods for each handleTypeX

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51