super keyword


The super keyword in java is a reference variable which is used in sub class to refer to the instance variable of its immediate parent class (super class).

Usage of java super Keyword

1. Super can be used in sub class to refer to its immediate parent class instance variables and methods.

If the parent class and child class have same fields then we can use super keyword to access the data member or field of parent class.


Example:

class Student
{
    String name = "Raj";  
}

class Employee extends Student
{
    int empId=13;
    void display()
    {
        // prints Employee ID from Employee class
        System.out.println(empId);

        // prints name from Student class
        System.out.println(super.name);
    }
}

class SuperExample
{
    public static void main(String args[])
    {
        Employee emp=new Employee();
        emp.display();
    }
}

Output:

13
Raj

2. Super is used to differentiate the members of a super class from the members of a subclass, if they have same names.

Example:

class Teacher
{
    String name="Raj";
    void hobby()
    {
        System.out.println("Reading");
    }
}

class Student extends Teacher
{
    String name="Abhi";
    void hobby()
    {
        System.out.println("Playing");
    }

    void display()
    {
        // prints name from Student class
        System.out.println(name);

        // prints hobby from Student class
        hobby();

        // prints name from Teacher class
        System.out.println(super.name);

        // prints hobby from Teacher class
        super.hobby();
    }
}

class SuperExample
{
    public static void main(String args[])
    {
        Student st=new Student();
        st.display();
    }
}

Output:

Abhi
Playing
Raj
Reading

3. Super can be used to invoke the super class constructor from the subclass.

Example:

class Teacher
{
    Teacher()
    {
        System.out.println("Teacher's object is created");
    }
}

class Student extends Teacher
{
    Student()
    {
        //Note: Constructor of super class should be called first
        // calls constructor of Teacher class
        super();
        System.out.println("Student's object is created");
    }
}

class SuperExample
{
    public static void main(String args[])
    {
        // creates object of Student class
        Student st=new Student();
    }
}

Output:

Teacher's object is created
Student's object is created