In this post, you will learn about super keyword in Java and how to use it to call super class constructors and methods. In below example, Driver class extends Person class. From Driver class we have called the constructor and method of Person class using super keyword.

package inheritance;

/**
 * Created by ssalunke on 20/04/2016.
 */
public class SuperTest {

    public static void main(String [] args){
        Driver d = new Driver("Sagar","QLD-2627");
        d.displayName();
        d.displayDriverDetails();
    }

}

class Person{
    String name;

    public Person(String name){
        this.name = name;
        System.out.println("In Super class constructor");
    }

    public void displayName(){
        System.out.println("In Super class.. Name is -> " + this.name);
    }
}

class Driver extends Person{
    String regNo ;

    public Driver(String name, String reg){
        //Invoke constructor of Super class
        super(name);
        this.regNo = reg;
        System.out.println("In Base class (Driver) constructor");
    }

    public void displayDriverDetails(){
        //Invoke method from super class - displayName
        super.displayName();
        System.out.println("In Base classs (Driver) - regNo is -> "
                + this.regNo);
    }

}
Here is the output of above Java example.

In Super class constructor
In Base class (Driver) constructor
In Super class.. Name is -> Sagar
In Super class.. Name is -> Sagar
In Base classs (Driver) – regNo is -> QLD-2627

Web development and Automation testing

solutions delivered!!