我有多个扩展父类的子类。
我想“强制”子类在每个子类中声明一个方法列表。
class childClass_A{
function interfaceMethod(){}
}
class childClass_B{
function interfaceMethod(){}
}
etc.
Run Code Online (Sandbox Code Playgroud)
为了做到这一点,我研究了接口。
我知道我可以让所有子类实现特定的接口,但这不是多余的代码吗?
class childClass_A implements MyInterface{
function interfaceMethod(){}
}
class childClass_B implements MyInterface{
function interfaceMethod(){}
}
etc.
Run Code Online (Sandbox Code Playgroud)
相反,我想到让父类实现该接口。
class parentClass implements MyInterface{
function interfaceMethod(){}
}
class childClass_A extends parentClass{
}
Run Code Online (Sandbox Code Playgroud)
但是,通过这样做,声明接口方法的“义务”被分配给父类,并且如果子类不包含接口的方法之一,则不会生成错误。
是否可以确保父对象的接口方法也在子类中声明?
您可以将父类声明为抽象类,并将所需的方法也声明为抽象类。
这样,子类必须实现这些方法,就像接口一样,否则它们无法实例化。
如果您需要为特定子类重用一个或多个方法,您可以考虑在特征中定义它们。
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |