简体   繁体   中英

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.

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.

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.

You should do neither. Adding this. is just superfluous and adding super. is likely to break your class if in the future you override getSkills() . So just do:

Skill[] x = getSkills();

In the current situation it will simply call the method defined in the superclass, if in the future you have a reason to override getSkills() (eg because your class uses a different way, or has additional conditions), it will be used automatically; which is more likely to be the correct behavior than continuing to call the superclass method.

In general you should only call super.someMethod() inside the overridden method if you need it (eg to not duplicate some logic or side-effects). Using it in another method should only be done if you are sure that you don't want your own implementation, but that of your superclass.

我认为你可以使用,因为支持是冠军,但使用super.getSkills会使代码更清晰,你在超类中调用一个方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM