super Keyword
Introduction: 9.4.0
- Sometimes you might want to call the superclass method even after overriding it
- Use
super.method()
to force a parent method to be called
- Use
- Super can be used in 2 ways:
super();
orsuper(args);
to call the superclass constructorsuper.method();
to explicitly call a superclass method
- This works because of how methods are called
- When a method is called, a class looks for the method starting in the class that created the call
- If it doesn’t find the method, it moves up to the parent
- This chain continues until we find the method
- If it doesn’t find the method, it moves up to the parent
- By explicitly calling
super
, we are using the object reference to the parent class, which skips the method in the child, and calls the parent method. - super calls do not stay in the superclass!!
public class Base
{
public void methodOne()
{
System.out.print("A");
methodTwo();
}
public void methodTwo()
{
System.out.print("B");
}
}
public class Derived extends Base
{
public void methodOne()
{
super.methodOne();
System.out.print("C");
}
public void methodTwo()
{
super.methodTwo();
System.out.print("D");
}
}
Derived d = new Derived();
d.methodOne();
/* Call trace:
* Derived.methodOne()
* Base.methodOne()
* print "A"
* Derived.methodTwo() // even though it's being called from the superclass!
* Base.methodTwo()
* print "B"
* print "D"
* Print "C"
*
* Output: "ABDC"
*/
toString()
is often a method which is overridden- A subclass can override this and then call
toString
in the new method to include both the old and newtoString
s in the output
- A subclass can override this and then call
Summary: 9.4.2
- The keyword
super
can be used to call a superclass’s constructors and methods - The superclass method can be called using a subclass by using the keyword
super
with the method name and appropriate parameters
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.