Polymorphism doesn't work right

I have an interface called Dictionary which has a method insert()

. This interface is implemented by the class BSTree

, but I also have a class AVLTree

that is a child class BSTree

. AVLTree

overrides insert()

to match it. Now if I type the following code:

Dictionary data=new AVLTree();
data.insert();

      

The problem arises because the method insert()

that is called has BSTree

instead AVLTree

. Why isn't polymorphism here? What is a suitable solution that preserves the principle of polymorphism?

+1


source to share


4 answers


In java, (I'm talking about C ++), polymorphism should "always" work. It's hard to figure out what's wrong without looking at the code. Maybe you could post an interesting part? For example, method signature, class declaration, etc. I am assuming that you did not use the same signature for both methods.



+1


source


When you say that AVLTree "overrides" insertion, what exactly do you mean? It must override the method, which means it has exactly the same signature (modulo).

Could you please post insert () signatures in both BSTree and AVLTree?



If you apply @Override annotation in AVLTree (assuming a suitable recent JDK), you should get a warning / error if you don't have the correct signature.

+6


source


You need to provide additional code snippets. I suppose it looks something like this:

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 should really work. Maybe you used a private or latest modifier somewhere?

Hello

+2


source


I have already decided. In the Dictionary interface, the function looked like insert (Object x), BSTree adhered to this requirement and defined the parameter as Object, but in AVLTree the parameter was comparable, after changing it to Object it worked.

Thank you anyway:)

+2


source







All Articles