Way2Java

super Keyword Java

We know earlier, in method overriding, the subclass method supersedes the super class method. When the method is overridden in inheritance, the subclass object calls its own method. If it calls its own method, the subclass looses the functionality of the super class method (of course, subclass is at liberty). If the subclass would like to call the super class method also, the subclass can do so using "super" keyword. "super" keyword is used by the subclass to call that of super class also when the methods or variables are overridden. "super" keyword can be used with instance variables and methods but not with classes.

1. super with Methods

In the following program, subclass overrides the eat() method of super class and at the same uses both with "super" keyword.

class Bird
{
  public void eat()
  {
    System.out.println("Eats insects.");
  }
}
public class Sparrow extends Bird
{
  public void eat()
  { 
    super.eat();
    System.out.println("Eats grains.");
    super.eat();                     // again you can call
  }
  public static void main(String args[])
  {
    Sparrow s1 = new Sparrow();
    s1.eat();
  }
}

Output screen of Sparrow.java

The eat() method exists in both Bird and Sparrow classes. We say, super class method is overridden by subclass. s1.eat() calls its own (Sparrow) method. Sparrow uses "super.eat();" to call Bird's eat() method. The next program illustrates "static" with variables.

Note:

  1. "super" keyword cannot be used from static methods like main().
  2. Static methods cannot be overridden (cannot be called with super keyword).

2. super with Variables

You have seen earlier "super" with methods. Let us go for with variables.

class Packing
{
  int cost = 50;
}
public class TotalCost extends Packing
{
  int cost = 100;
  public void estimate()
  {
    System.out.println("Cost of articles Rs." + cost);
    System.out.println("Packing expenses Rs." + super.cost);
    System.out.println("Total to pay Rs." + (cost + super.cost));
  }
  public static void main(String args[])
  {
    TotalCost tc1 = new TotalCost();
    tc1.estimate();
  }
}

Output screen of TotalCost.java

In the above code, cost variable of Packing class is overridden by TotalCost. In this case, the subclass object prefers to call its own variable. super.cost calls super class cost variable. super.cost cannot be called from static methods like main() method.

Programming Tip: Do not attempt to use super keyword with classes. It is a compilation error.

"super" and "this"

In java, "super" keyword is used to call super methods and variables (when overridden only, else, not necessary to use) and "this" keyword is used to refer the current object.