Question

I have three classes, a test class, a shape class, and a geometricObject class. The shape class extends the geometricObject class (geometricObject class is abstract). The thing is, the shape class and the geometricObject have the same toString method but the contents of the two are different. When I call the toString method in the test class, I get the results from the toString method in the shape class. When I try to cast the object I created into the geometricObject class and try to call upon the toString method there, I still get the same result from the shape class toString method. So does the superclass overwrite methods in abstract/subclasses if they have the same name/argument list?

Was it helpful?

Solution

The behavior you're seeing here is due to polymorphism and function overloading. If you have a toString() method in the base class and the derived class, it will always call the most derived version of the toString() method, which is in the derived class. It doesn't matter how you are holding the reference to the derived class (e.g. in a derived class reference, a base class reference, or an object reference).

This is true whether the base class implements the toString() method, or just declared it. It's also true for all other methods as well - toString() is not special aside from the fact that it's part of Object's basic contract.

So, you'll see the same behavior here even if you cast your derived class to Object and call toString() on that.


PS: You should annotate your overridden methods, like toString() using @Override in Java to make it more explicitly recognizable - a lot of tooling/IDEs work on this concept.

OTHER TIPS

if your geometricObject class is abstract, then all it can have for a toString() method is:

public String toString();.

No method body.

In any case, toString() is inherited from the parent of all classes, Object.

If your class Shape extends geometricObject and defines its own toString(), which it should, then yes, you will get exactly what is specified in the toString() of the Shape class.

For more about method overriding, see http://docs.oracle.com/javase/tutorial/java/IandI/override.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top