2012-01-18 65 views
2

我做了一个类树(数学表达式的抽象)。它嵌套了类“顶点”和“顶点头”。另一个类“BinaryTree”扩展了Tree,但它具有更多的可能性,因为它是Binary,它们有不同的顶点类(我添加到顶点方法giveRight和giveLeft),这就是为什么我使用嵌套类的继承。但我有场从树头,它没有giveRight方法等等......这里有一个例子:面向对象编程。子类的域

class Tree{ 
    class Vertex{ 
     //smth 
    } 
    Vertex head; 
} 

class BinaryTree extends Tree{ 
    class Vertex extends Tree.Vertex{ 
     //added methods... 
    } 
    //problem with head element, it is element of Tree.Vertex 
} 

我说的对这个问题的面向对象的一部分?或者我应该从树中删除头字段,并将其仅添加到它的子类中。

谢谢。

回答

8

主要问题不是head字段的声明类型,而是其运行时类型。如果子类是唯一创建自己的顶点的子类,则它可以将BinaryTree.Vertex分配给head变量。不过,如果您想使用其他方法,则必须将其转换为BinaryTree.Vertex

为了避免转换,你可以使树类通用:

public class Tree<V extends Vertex> { 
    protected V head; 
} 

public class BinaryTree extends Tree<BinaryVertex> { 

} 

关于泛型更多信息,请参阅javadoc