Do not use the super keyword to refer to other methods that are not overridden. This is confusing for other developers trying to extend your classes.
Look at the code that uses the super keyword this way. Here we have 2 classes: Dog and CleverDog :
public static class Dog extends Animal { private String name; public Dog(String name) { this.name = name; } public String getName() { return name; } } public class CleverDog extends Dog { public CleverDog(String name) { super(name); } public void rollover() { System.out.println(super.getName()+" rolls over!"); } public void speak() { System.out.println(super.getName() + " speaks!"); } }
Now imagine that you are a new project developer and you need certain behavior for a smart dog that is on TV: this dog should do all its tricks, but must follow its fictitious name for the TV. To do this, you override the getName(...) method ...
public class DogOnTv extends CleverDog { String fictionalName; public DogOnTv(String realName, String fictionalName) { super(realName); fictionalName = fictionalName; } public String getName() { return fictionalName; } }
... and fall into the trap set by the original developer, and their unusual use of the super !
The code above will not work, because in the original implementation of CleverDog getName() is called using the super keyword. This means that it always calls Dog.getName() - not related to any override. Therefore, when you use your new DogOnTv type ...
System.out.println("Showcasing the Clever Dog!"); CleverDog showDog = new CleverDog("TugBoat"); showDog.rollover(); showDog.speak(); System.out.println("And now the Dog on TV!"); DogOnTv dogOnTv = new DogOnTv("Pal", "Lassie"); dogOnTv.rollover();
... you get the wrong conclusion:
Showcasing the Clever Dog! Tugboat rolls over! Tugboat speaks! And now the Dog on TV! Pal rolls over! Pal speaks!
This is not the usual expected behavior when overriding a method, so you should avoid creating such confusion by using the super keyword where it does not belong.
If, however, this is really the behavior you want, use the final keyword instead - to clearly indicate that the method cannot be overridden:
public class CleverDog extends Dog { public CleverDog(String name) { super(name); } public final String getName() {