2016-04-14 112 views
0

假设我有一个扩展类父类的子类。 Child类有两个嵌套类nested1和nested2。我想要一个抽象函数在Parent中用参数定义为nested1并且返回类型为嵌套2.现在,为了达到这个目的,我创建了一个函数,它的参数和返回类型都是Object。使用嵌套对象处理父类和子类的继承

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

还附上了UML enter image description here

回答

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; 
    } 
} 

在更广泛的范围内,您应该问自己为什么每个孩子都需要自己的一套嵌套类。如果可以将嵌套类定义移动到父类(并使其成为静态),并且只需在构造过程中根据需要对子类进行定制,则这将变得更简单。

+0

谢谢! 。嵌套类的定义在所有孩子中是不同的。所以我无法将它们作为独立的静态类。你能想出一种方法来改进设计吗? – mc20

+0

鉴于这一点,设计问题是为什么你需要父项中的抽象方法?假设我有'Parent p = ...',我不知道它的类型,我可以用正确的参数调用'p.func(...)'吗?如果不是抽象方法没有意义的话 – Mshnik