使用嵌套对象处理带有Parent Class和Child Classes的继承

时间:2016-04-14 19:46:05

标签: java oop ooad

假设我有一个Child扩展Class Parent。 Child类有两个嵌套类nested1和nested2。我希望在Parent中定义一个抽象函数,其参数为nested1,返回类型为嵌套2.现在,为了实现这一点,我创建了一个函数,其参数和返回类型都是Object。

所以现在,当我实现子类时,我总是需要将Object转换为nested1和nested2。我觉得有更好的方法来实现这一目标。有没有更好的方法来降低复杂性?

还附上了UML enter image description here

1 个答案:

答案 0 :(得分:3)

从打字的角度来看,最好的方法是在父类中创建一个指定子节点中嵌套类的接口。这样你就不需要将参数强制转换为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;
  }
} 

在更广泛的范围内,您应该问问自己为什么每个孩子都需要自己的一组嵌套类。如果您可以将嵌套的类定义移动到父级(并使它们保持静态),并且让子类在构造期间根据需要自定义它们,这将变得更简单。