Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this. or super. when calling a method that exist in a superclass and a subclass

There is a class called Champion who have an array of Skill as an instance variable.

It implement a method called "public final Skill[] getSkills()" where Skill[] is an array of another object called Skill.

There is a subclass called Support that implement a method called "public final boolean canHeal()" that check the array of skills in the method canHeal.

Should I write" Skill[] x = this.getSkills() " or : Skill[] x = super.getSkills() " to get the array of Skill and why ?

Keep in mind that the method getSkills is only defined in class Champion and not overridden in class Support.

Thanks in advance.

like image 259
MChawa Avatar asked Jan 18 '26 10:01

MChawa


2 Answers

The super keyword allows you to call the base class' version of a method that your class overrode or shadowed.

If you class doesn't have a separate getSkills() method, super will have no effect.

like image 71
SLaks Avatar answered Jan 21 '26 02:01

SLaks


I think it is better to call the function without super.

First of all - for now there is now difference. In the future, if you'll override this function in your class it will be hard to spot (or at least need attention).

In case you override your function, you might want to call super.getSkills() inside it.

like image 37
BobTheBuilder Avatar answered Jan 21 '26 01:01

BobTheBuilder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!