Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using super to call methods other than the one being overridden not recommended?

In oracle tutorial, it says: If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

It mentioned about the use of super in overridden method.

However, I reality, in the sample program I wrote, I can use super keywords to access any method in the superclass.

The question here is: why most people talking online about the use of super, they always talking about the invocation of overridding method?

I mean, why that "use super to call other method in superclass" is not recommended?


BTW, one more question here: we can't use super in static method. The compiler won't let us do that.

Is it because the variable "super" belongs to an object instead of the class, just like keyword "this"?. A static method belongs to a class, and the static method doesn't have the variable "super"?

like image 402
Fan Zhang Avatar asked Jan 11 '23 13:01

Fan Zhang


1 Answers

Why using super.foo() outside method foo() is a bad idea

It suggests the old method is still needed (and does something different from the child version of the method), in which case you probably shouldn't be overriding it in the first place. The parent method still "makes sense" within the child object.

Two identically named methods both being used within the same object but with different effects sounds like a nightmare for readability. Given that both are being used it seems highly likely that they should be separate methods with different method names making their subtle difference clear.

Why using super.foo() to refer to a method that isn't overridden is a bad idea

This semantically is a very odd thing to write. A parents (non private) methods are the childs methods unless overridden, using super.method() has an identical effect to method() and so it is not surprising you have not seen this mentioned. As you have supposed it is also very likely to cause bugs in the future if you later do override the method.

Similarly to this you can put public on the front of interface methods but it has no effect.

Why you can't use super with static methods

Static methods cannot be overridden, if a parent class and a child class happen to have the same method name that is simply a coincidence as far as the compiler is concerned (although it does hide the static method in the parent class - it does not override it). Given that a static method cannot be overridden using the super keyword to access one becomes meaningless. Furthermore you can access a static method in Foo as

Foo.staticMethod();

like image 169
Richard Tingle Avatar answered Feb 03 '23 12:02

Richard Tingle