14 May 2015

Usage of Super Keyword in Java with Example

Super keyword is used to access members of super class from its sub class. If a method overrides one of its super class's methods then you can call the overridden method through super keyword from sub class.

Let's see the usage of super keyword with examples.

Example to illustrate how to invoke super class method using super keyword
// Super Class
class A{
   public void display(){
      System.out.println("Super Class Method");
   }
}
// Sub Class
class B extends A{
   public void display(){
      super.display();   // Invoke Overridden Method
      System.out.println("Sub Class Method");
   }
}
public class Test{
   public static void main(String args[]){
      B obj = new B();
      obj.display();
   }
}
Output:
Super Class Method
Sub Class Method

In the preceding program we have a super class A and its sub class B which overrides display() method. Then, inside main() method we are creating an instance of sub class B and invoking its display() method. Inside sub class display() method we are invoking overridden super class display() method by using super keyword.

We can also invoke super class constructor by using super keyword and its syntax:
super();   /* Invokes super class no-argument constructor */
super(parameter list);   /* Invokes super class constructor with
                            matching parameter list */

Example to illustrate how to invoke super class constructor using super keyword
// Super Class
class A{
   public A(){
      System.out.println("Super Class Constructor");
   }
}
// Sub Class
class B extends A{
   public B(){
      super();   /* Invoke Super Class Constructor and this
                    statement must always be first statement */
      System.out.println("Sub Class Constructor");
   }
}
public class Test{
   public static void main(String args[]){
      B obj = new B();
   }
}
Output:
Super Class Constructor
Sub Class Constructor

In the preceding program we defined no-argument constructor inside super class A and its sub class B. Then, inside main() method we are creating an instance of sub class B so that its no-argument constructor is being called. Inside sub class no-argument constructor we are invoking super class no-argument constructor by using super keyword.

Point to Remember: Calling a constructor statement must always be the first statement inside a constructor.





Popular Posts

Write to Us
Name
Email
Message