I made a class Tree (abstraction for mathematical expression). It have nested class ‘Vertex’ and field ‘Vertex head’. Another class ‘BinaryTree’ extends Tree, but it have more possibilities since it’s Binary and they have different Vertex classes (I added to Vertex methods giveRight and giveLeft), that’s why I use inheritance of nested classes. But I have field from Tree head, and it doesn’t have methods giveRight and so on… Here is an example:
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
}
Am I right with object-oriented part of this problem? Or should I delete head field from Tree and add it only to it’s subclasses.
Thank you.
The main problem is not the declared type of the
headfield, but its runtime type. If the subclass is the only one to create its own vertices, then it can assign aBinaryTree.Vertexto theheadvariable. You’ll have to cast if toBinaryTree.Vertexif you want to use its additional methods, though.To avoid the cast, you may make the Tree class generic:
See javadoc for more information about generics.