You are here

Calling methods of the superclass

15 January, 2016 - 09:02
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6

When concrete methods or the constructor of a superclass are overriden, sometimes it is necessary or desirable to call the original superclass behavior from the subclass. A common reason for this is that the subclass's behavior is simple an addition to the superclass behavior. One does not want to replicate the superclass code, so a call to the superclass's original methods is required at some point in the subclasses overriding method. To accomplish this, Java uses the super keyword. super refers to the superclass instance, just as this refers to the class instance itself (the subclass here). Note that technically, super and this are the same object think of it as the difference between the id and the ego. (Does that mean that a coding mistake with respect to super and this is a Freudian slip?)

Suppose the superclass has a method called myMethod() which the subclass overides. For the subclass to call the superclass's myMethod, it simply needs to say super.myMethod(). Contrast this to the subclass calling its own myMethod: this.myMethod() (note: Java syntax rules allow for the this to be omitted).

To make a call to the superclass's constructor the subclass simply says super(...), supplying whatever parameters the superclass constructor requires. This is a very common scenario as the subclass almost always needs to superclass to initialize itself before it can perform any additional initializations. Thus the super(...) call must be the first line in the subclass's constructor. If the no-parameter constructor of the superclass is required, the call to super can be omitted as it will be automatically performed by the Java run-time engine. This of course presumes that the superclass's no-parameter constructor exists, which it does not if a parameterized constructor has been declared without explicitly declaring the no-parameter constructor.