【发布时间】:2016-10-21 11:44:45
【问题描述】:
我有一个 java 类。
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(){}
}
现在我必须添加对类型 3 和类型 4 的支持。但是我不能修改 ClassA 的代码。
所以我想我会编写 ClassB 来扩展 ClassA 并添加对 type3 和 type 4 的支持,如下所示。
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(){}
}
我认为这会奏效。但是我在 ClassB 的构造函数中得到了“Call to super() must be first statement in constructor body”错误。
我阅读了this post 并理解为什么 super() 必须是构造函数中的第一个语句。
我可以通过在 ClassB 中编写 ClassA 的完整代码并添加对类型 3 和 4 的支持来解决我的用例。但我想知道是否有更好的解决方案来解决这个问题。
【问题讨论】:
-
遇到这样的疑惑,我觉得app架构有问题……
标签: java inheritance constructor