我制作了一个类Tree(数学表达式的抽象)。它有嵌套类'Vertex'和字段'Vertex head'。另一个类'BinaryTree'扩展了Tree,但它有更多的可能性,因为它是Binary并且它们有不同的Vertex类(我添加到Vertex方法giveRight和giveLeft),这就是我使用嵌套类的继承的原因。但是我有来自Tree head的字段,它没有方法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
}
我对这个问题的面向对象部分是否正确?或者我应该从Tree中删除head字段并将其仅添加到它的子类中。
谢谢。
答案 0 :(得分:8)
主要问题不是head
字段的声明类型,而是其运行时类型。如果子类是唯一一个创建自己的顶点的子类,那么它可以为BinaryTree.Vertex
变量分配head
。但是,如果要使用其他方法,则必须将if转换为BinaryTree.Vertex
。
为避免强制转换,您可以将Tree类设为通用:
public class Tree<V extends Vertex> {
protected V head;
}
public class BinaryTree extends Tree<BinaryVertex> {
}
有关泛型的详情,请参阅javadoc。