user197284
user197284

Reputation: 281

Object-oriented programming. Field of the subclass

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.

Upvotes: 2

Views: 140

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

The main problem is not the declared type of the head field, but its runtime type. If the subclass is the only one to create its own vertices, then it can assign a BinaryTree.Vertex to the head variable. You'll have to cast if to BinaryTree.Vertex if you want to use its additional methods, though.

To avoid the cast, you may make the Tree class generic:

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

public class BinaryTree extends Tree<BinaryVertex> {

}

See javadoc for more information about generics.

Upvotes: 8

Related Questions