Super Keyword In Java - Java Tutorial

Super Keyword In Java

BLUF: Mastering Super Keyword In Java is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Super Keyword In Java

Java's versatility is unmatched. Learn how Super Keyword In Java fits into the Java ecosystem and improves your code structure in the tutorial below.

In Java, the super keyword enables a subclass to utilize methods, variables, or constructors from its direct parent class.

What is super Keyword in Java?

The super keyword serves as a reference variable that points to the object of the parent class directly. Each time you instantiate a subclass, an object of the parent class is automatically created, and this can be accessed through the super reference variable.

Advantages of Using super Keyword

Here are the advantages of using the super keyword in Java:

  • Simplifies Constructor Chaining: The super call ensures that the parent class's constructor is executed before the child class's, maintaining proper initialization across the inheritance hierarchy.
  • Access to Overridden Methods: It allows a subclass to invoke a method from the parent class even when the subclass has overridden the method. This is useful for extending functionality without completely overriding it.
  • Access to Hidden Fields: It provides access to parent class fields that subclass fields may hide with the same name.
  • Code Reusability: By invoking the parent class's methods or constructors, it promotes code reuse and reduces redundancy.
  • Maintains Hierarchical Relationships: It preserves and utilizes the hierarchical structure of inheritance, making the code more organized and easier to manage.
  • Using super to Access Parent Class Instance Variables

The super keyword is utilized to retrieve the data member or field from the parent class in scenarios where both the parent class and the child class possess identical fields.

The illustration below showcases the utilization of the super keyword to retrieve an instance variable from the parent class when it is concealed by a subclass variable.

Example

Example

//Java Program to illustrate the use of super keyword

//Creating parent class

class Animal{  

    String color="white";  

}  

//Creating child class

class Dog extends Animal{  

    String color="black";  

    void printColor(){  

        System.out.println(color);//prints color of Dog class  

        System.out.println(super.color);//prints color of Animal class  

    }  

}  

//Creating Main class to create object and call methods

public class Main{  

    public static void main(String args[]){  

        Dog d=new Dog();  

        d.printColor();  

    }

}

Output:

Output

black

white

In the scenario provided, the classes Animal and Dog share a common attribute called color. When we output the color attribute, it will display the color specific to the current class as the default behavior. To retrieve the property from the parent class, we utilize the super keyword.

Using super to Invoke Parent Class Methods

The super keyword is also utilized to call the method of the parent class. Its usage is necessary when the subclass has a method that matches the one in the parent class, indicating method overriding.

The illustration below showcases the utilization of the super keyword to invoke a method of the superclass from a subclass.

Example

Example

//Java Program to illustrate the use of super()

//Creating parent class

class Animal{  

    void eat(){System.out.println("eating...");}  

}  

//Creating child class

class Dog extends Animal{  

    void eat(){System.out.println("eating bread...");}  

    void bark(){System.out.println("barking...");}  

    void work(){  

        super.eat();  

        bark();  

    }  

}  

//Creating Main class to create object and call methods

public class Main{  

    public static void main(String args[]){  

        Dog d=new Dog();  

        d.work();  

    }

}

Output:

Output

eating...

barking...

In the scenario discussed, both the Animal and Dog classes contain the eat method. When invoking the eat method from the Dog class, it will automatically execute the eat method of the Dog class due to the precedence given to local methods.

In order to invoke the method of the superclass, it is necessary to utilize the super keyword.

Using super to Invoke Parent Class Constructor

The super keyword is also utilized for calling the constructor of the parent class. Let's examine a straightforward illustration:

Below is an illustration showcasing the utilization of the super keyword to invoke the constructor of the superclass from a subclass.

Example

Example

class Animal{  

    Animal(){System.out.println("animal is created");}  

}  

class Dog extends Animal{  

    Dog(){  

        super();  //calls the constructor of parent class

        System.out.println("dog is created");  

    }  

}  

public class Main{  

    public static void main(String args[]){  

        Dog d=new Dog();  

    }

}

Output:

Output

animal is created

dog is created

Note: super is added in each class constructor automatically by the compiler if there is no super or this.

It is common knowledge that in the absence of a constructor, the compiler automatically includes a default constructor. Additionally, the compiler inserts super as the initial statement.

Another Example: Using super Keyword

An additional illustration of the super keyword is when the compiler automatically includes super.

Example

Example

class Animal{  

    Animal(){System.out.println("animal is created");}  

}  

class Dog extends Animal{  

    Dog(){  

        System.out.println("dog is created");  

    }  

}  

public class Main{  

    public static void main(String args[]){  

        Dog d=new Dog();  

    }

}

Output:

Output

animal is created

dog is created

Real-Time Use of Super Keyword

Consider the practical application of the super keyword. In this scenario, the Emp class is deriving from the Person class, which means that all attributes of the Person class will be automatically inherited by Emp. To set up all the attributes, we are utilizing the constructor of the parent class within the child class. This approach allows us to effectively utilize the constructor of the parent class.

Let's consider an example to illustrate the practical application of the 'super' keyword in Java programming.

Example

Example

class Person{  

    int id;  

    String name;  

    Person(int id,String name){  

        this.id=id;  

        this.name=name;  

    }  

}  

class Emp extends Person{  

    float salary;  

    Emp(int id,String name,float salary){  

        super(id,name);//reusing parent constructor  

        this.salary=salary;  

    }  

    void display(){System.out.println(id+" "+name+" "+salary);}  

}  

public class Main{  

    public static void main(String[] args){  

        Emp e1=new Emp(1,"ankit",45000f);  

        e1.display();  

    }

}

Output:

Output

1 ankit 45000

Characteristics of super Keyword

Here are the primary features of the super keyword in the Java programming language:

1. Calling the Parent Class Constructor

In Java, when an instance of a subclass is instantiated, the constructor of the superclass is invoked automatically. To explicitly invoke the constructor of the superclass, the super keyword is used. This practice is commonly employed to guarantee that the superclass is appropriately initialized prior to the commencement of the subclass.

2. Calling a Parent Class Method

When a method is replaced in the child class after being inherited from the parent class, the child class can access the original version of that method from the parent class by utilizing super.methodName. This approach is beneficial when the child class aims to enhance or append additional features to the method while retaining access to the initial functionality provided by the parent class.

3. Accessing Parent Class Fields

When both the parent and child classes contain variables (fields) with identical names, the 'super' keyword enables the child class to access the parent class's version of the field. This feature is beneficial in preventing ambiguity between the two variables and explicitly indicating that we are accessing the one located in the parent class.

4. First Statement in Constructor

To invoke the parent class's constructor using super, it is essential to place this call as the initial statement within the child class's constructor. This guarantees that the parent class is properly initialized before the child class commences its own initialization process.

5. Cannot Be Used in Static Contexts

The usage of the super keyword is restricted within static methods or static variables due to their association with the class rather than a particular object. As super pertains to the parent class of an object, it is not permissible within static contexts.

6. Not Always Necessary

When the method of the parent class is not redefined in the child class, the utilization of super to invoke the parent class's method is unnecessary. The parent class's method will be automatically invoked by the child class when the method is called.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience