tags:

views:

189

answers:

4
+1  Q: 

Polymorphism

Hello,

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?

Thank you in advance.

Best regards, Daniel

+6  A: 

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.

Jon Skeet
+1  A: 

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.

+2  A: 

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

huo73
+2  A: 

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

Daniel
Sounds like you need to include some generic typing on your classes.
JeeBee
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
I have to have 15 rep points for voting. When I reach them, I promise I'll vote up one:)
Daniel
You don't need points to mark an answer as correct (the checkmark below the voting controls)
Michel
Daniel,This is an excellent reason to use the @Override annotation.
Matt Solnit