I’m trying to get the hang of inheritance in Java and have learnt that when overriding methods (and hiding fields) in sub classes, they can still be accessed from the super class by using the ‘super’ keyword.
What I want to know is, should the ‘super’ keyword be used for non-overridden methods?
Is there any difference (for non-overridden methods / non-hidden fields)?
I’ve put together an example below.
public class Vehicle {
private int tyreCost;
public Vehicle(int tyreCost) {
this.tyreCost = tyreCost;
}
public int getTyreCost() {
return tyreCost;
}
}
and
public class Car extends Vehicle {
private int wheelCount;
public Vehicle(int tyreCost, int wheelCount) {
super(tyreCost);
this.wheelCount = wheelCount;
}
public int getTotalTyreReplacementCost() {
return getTyreCost() * wheelCount;
}
}
Specifically, given that getTyreCost() hasn’t been overridden, should getTotalTyreReplacementCost() use getTyreCost(), or super.getTyreCost() ?
I’m wondering whether super should be used in all instances where fields or methods of the superclass are accessed (to show in the code that you are accessing the superclass), or only in the overridden/hidden ones (so they stand out).
Don’t use the
superkeyword to refer to other methods which aren’t overridden. It makes it confusing for other developers trying to extend your classes.Let’s look at some code which does use the
superkeyword in this way. Here we have 2 classes:DogandCleverDog:Now, imagine you are a new developer on the project, and you need some specific behavior for a clever dog who is on TV: that dog has to do all its tricks, but should go by its fictitious TV name. To accomplish this, you override the
getName(...)method…… and fall into a trap set by the original developer and their unusual use of the
superkeyword!The code above isn’t going to work – because in the original
CleverDogimplementation,getName()is invoked using thesuperkeyword. That means it always invokesDog.getName()– irrelevant of any overriding. Consequently, when you use your newDogOnTvtype…… you get the wrong output:
This is not the usual expected behavior when you override a method, so you should avoid creating this kind of confusion using the
superkeyword where it doesn’t belong.If, however, this is actually the behavior you want, use the
finalkeyword instead – to clearly indicate that the method can’t be overridden: