【问题标题】:Handling inheritance with Parent Class and Child Classes with nested objects使用嵌套对象处理父类和子类的继承
【发布时间】:2016-04-14 19:46:04
【问题描述】:

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

所以现在,当我实现子类时,我总是需要将对象转换为嵌套 1 和嵌套 2。我觉得会有更好的方法来实现这一点。有没有更好的方法来降低复杂度?

还附上了UML

【问题讨论】:

    标签: java oop ooad


    【解决方案1】:

    从打字的角度来看,最好的方法是在父类中创建一个接口,指定子类中的嵌套类。这样您就不需要将参数强制转换为 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(...)吗?如果没有,那么抽象方法就没有意义
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    相关资源
    最近更新 更多