Using Super to call an Overridden MethodΒΆ

Sometimes you want the child class to do more than what a parent method is doing. You want to still execute the parent method, but then do also do something else. But, since you have overridden the parent method how can you still call it? You can use super.method() to force the parent’s method to be called.

public class Person
{
   private String name = null;

   public Person(String theName)
   {
      name = theName;
   }

   public String getFood()
   {
      return "Hamburger";
   }
}

public class Student extends Person
{
   private int id;
   private static int nextId = 0;

   public Student(String theName)
   {
     super(theName);
     id = nextId;
     nextId++;
   }

   public String getFood()
   {
      String output = super.getFood();
      return output + " and Taco";
   }

   public int getId(return id);
   public int setId (int theId)
   {
      this.id = theId;
   }
}

When the student getFood() method is executed it will start executing the getFood method in Student. When it gets to super.getFood() it will execute the getFood method in Person. This method will return the string "Hamburger". Then execution will continue in the getFood method of Student and it return return the string "Hamburger and Taco".

10-4-1: Given the following class declarations, and assuming that the following declaration appears in a client program: Base b = new Derived();, what is the result of the call b.methodOne();?

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");
   }
}