1

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?

4 Answers 4

6

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.

2

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

2

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 :)

5
  • Sounds like you need to include some generic typing on your classes.
    – JeeBee
    Dec 3, 2008 at 13:38
  • The earlier answers are all correct, as you discovered - it would be courteous to mark the one that you think will be most helpful to later searchers of this issue accepted.
    – Greg Case
    Dec 3, 2008 at 13:41
  • I have to have 15 rep points for voting. When I reach them, I promise I'll vote up one:)
    – Daar
    Dec 3, 2008 at 13:55
  • You don't need points to mark an answer as correct (the checkmark below the voting controls)
    – Michel
    Dec 3, 2008 at 14:06
  • Daniel, This is an excellent reason to use the @Override annotation. Dec 3, 2008 at 20:47
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.