Super keyword in java

The super keyword in Java is used to refer immediate parent class object. Super can be used to invoke immediate parent class method or constructor. super () acts as an immediate parent class constructor and should be the first line in the child class constructor.

 

Use case demonstrating super with variables

 
class Info {
    String name = "Web";
}
class Student extends Info {
    String name = "App";
    void printName() {
        System.out.println(name);//prints the name of subclass
        System.out.println(super.name);//prints the name of superclass
    }
}
public class TestSuper1 {
    public static void main(String args[]) {
        Student s = new Student();
        s.printName();
    }
}

 

 Output:

App
Web

 

In the above example when the student object s is created student class is executed which contains the method printName inside which we have a variable super. the name that will execute its superclass info and print the name given in the superclass which is "Web"

 

Use case demonstrating super with methods

 
class Info {
    void marks() {
        System.out.println("marks of Web");
    }
}
class Student extends Info {
    void marks() {
        System.out.println("marks of App");
    }
    void grade() {
        System.out.println("Dev");
    }
    void data() {
        super.marks();
        grade();
    }
}
public class TestSuper2 {
    public static void main(String args[]) {
        Student s = new Student();
        s.data();
    }
}  

 

Output:

marks of Web
Dev

 

In the above example, when the student object is created, it executes the student class, extending its superclass info. During the execution, it contains super. marks() which will execute the marks method inside the superclass info and the statements inside the marks method are executed here ”marks of Web” is printed

 

Use case demonstrating super with constructors

 
class PersonalInfo {
    PersonalInfo() {
        System.out.println("Inside PersonalInfo");
    }
}
class Student extends PersonalInfo {
    Student() {
        super();
        System.out.println("Inside Student");
    }
}
public class TestSuper3 {
    public static void main(String args[]) {
        Student s = new Student();
    }
}  

 

Output:

Inside personal info
Inside Student

 

In the above example once the object s is created the student constructor is executed inside which contains the super keyword that will execute the PersonalInfo constructor

 

 

Related Tutorials

Map