【发布时间】:2016-04-14 19:46:04
【问题描述】:
假设我有一个子类扩展父类。 Child 类有两个嵌套类nested1 和nested2。我希望在 Parent 中定义一个抽象函数,参数为嵌套 1,返回类型为嵌套 2。现在,为了实现这一点,我创建了一个参数和返回类型都为 Object 的函数。
所以现在,当我实现子类时,我总是需要将对象转换为嵌套 1 和嵌套 2。我觉得会有更好的方法来实现这一点。有没有更好的方法来降低复杂度?
【问题讨论】:
假设我有一个子类扩展父类。 Child 类有两个嵌套类nested1 和nested2。我希望在 Parent 中定义一个抽象函数,参数为嵌套 1,返回类型为嵌套 2。现在,为了实现这一点,我创建了一个参数和返回类型都为 Object 的函数。
所以现在,当我实现子类时,我总是需要将对象转换为嵌套 1 和嵌套 2。我觉得会有更好的方法来实现这一点。有没有更好的方法来降低复杂度?
【问题讨论】:
从打字的角度来看,最好的方法是在父类中创建一个接口,指定子类中的嵌套类。这样您就不需要将参数强制转换为 func。这本身并没有降低复杂性,但它确实让你的意图更清晰,并减少/消除了铸造的需要(总是一件好事)。
public abstract class Parent {
interface Interface1 {
//Specifications of methods that all child nested classes must have
}
interface Interface2 {
//Specifications of methods that all child nested classes must have
}
public abstract Interface2 func(Interface1 obj);
}
public class Child extends Parent {
private static class Impl1 implements Interface1 {
//Implementations of methods in Interface1 as they pertain to Child
}
private static class Impl2 implements Interface2 {
//Implementations of methods in Interface2 as they pertain to Child
}
@Override
public Interface2 func(Interface1 obj) {
//Should only have to use methods declared in Interface1
//Thus should have no need to cast obj.
//Will return an instance of Impl2
return null;
}
}
在更广泛的范围内,您应该问自己为什么每个孩子都需要自己的一组嵌套类。如果您可以将嵌套类定义移动到父类(并使它们成为静态),并让子类在构造过程中根据需要自定义它们,这将变得更简单。
【讨论】:
Parent p = ...,但我不知道它的类型,我可以用正确的参数调用p.func(...)吗?如果没有,那么抽象方法就没有意义