Reputation: 3555
I have an interface called Dictionary which has a method insert()
. This interface is implemented by class BSTree
, but I also have a class AVLTree
which is a child class of BSTree
. AVLTree
redefines the insert()
so it suits it's needs. Now if I type the following code:
Dictionary data=new AVLTree();
data.insert();
There is a problem, because the insert()
method that is called is of BSTree
instead of AVLTree
. Why doesn't the polymorphism kick in here? What is the appropriate solution, one that retains the principle of polymorphism?
Upvotes: 1
Views: 573
Reputation: 3555
Already solved it. In the interface Dictionary the function looked like insert(Object x), BSTree adhered to this demand and defined the parameter as Object, but in AVLTree the parameter was a Comparable type, after changing it to Object it worked.
Thanks anyway :)
Upvotes: 2
Reputation: 599
You have to provide more code snippets. I suppose it looks something like that:
public Interface Dictionary {
...
public void insert();
...
}
public Class BSTree implements Dictionary {
...
public void insert() {
// some implementation here
}
...
}
public Class AVLTree extends BSTree {
...
public void insert() {
// another implementation of insert
}
...
}
This actually should work. Maybe you have used private or final modifier somewhere?
Regards
Upvotes: 2
Reputation: 2362
In java, (I'm talking relatively to C++), polymorphism should "always" work. It's hard to see what's wrong without looking at the code.. maybe you could post interesting part? Such as the method's signature, class declaration, etc.. My guess is that you haven't used the same signature for both methods.
Upvotes: 1
Reputation: 1499740
When you say AVLTree "redefines" the insert, what exactly do you mean? It has to override the method, which means having exactly the same signature (modulo variance).
Could you post the signatures of insert() in both BSTree and AVLTree?
If you apply the @Override annotation in AVLTree (assuming a suitably recent JDK) you should get a warning/error if you've not got the right signature.
Upvotes: 6