3

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

You can have a concrete method in an abstract class.
If the method is not abstract, then you must ensure it has at least an empty body {}, otherwise it won't compile. Maybe you're confusing abstract class with interface.
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. @ docs.oracle.com/javase/tutorial/java/IandI/abstract.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.