Calling an method of the superclass that calls another superclass method that's also overridden results in the first superclass method calling the overridden sub class method. Why does this happen?

Example Incorrect code: http://pastebin.com/W6v9xC2Z

Correct code: http://pastebin.com/zTHvUiBK

The only difference in the code is at Line 55 where I call the instance variable directly instead of using the getter method in the incorrect version.

The calls to the superclass method from subclass method happens at lines 73 and 91.

Why does this happen? Shouldn't the fact that I use super make the call only to superclass method?

Posted Jun 6, 2014, 1:35 AM UTC

11
Rhomboid•

The whole point of overriding a method is that the override happens everywhere the method is called, including in base classes. It would defeat the purpose if a method called in a base class ignored overridden methods. The toString in the base class is still being invoked on an object of type WeighedItem, so any overrides in WeighedItem still apply. Using super doesn't change anything -- the method has no way of knowing how it was called, it's not privy to that information. In order for it to work the way you imagine, the language would have to make an entire separate copy of the method with different behavior just so that it could call it on the off chance that the user used super. Worse, it couldn't anticipate when someone might want to do that, so it would have to make a second copy of every method of every class that ever calls a non-static/non-final method. Can you see how insane that's beginning to sound?

2