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
  • Super can be used in 2 ways:
    • super(); or super(args); to call the superclass constructor
    • super.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
  • 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 new toStrings in the output

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