Super in Java

 

The super keyword in Java is a reference variable that is used to refer to parent class when we’re working with objects. You need to know the basics of Inheritance and Polymorphism to understand the Java super keyword.

The Keyword “super” came into the picture with the concept of Inheritance. In this article, we gonna covers all about super in Java including definitions, examples, Uses, Syntax, and more


Characteristics of Super Keyword in Java

In Java, super keyword is used to refer to the parent class of a subclass. Here are some of its key characteristics:
  • super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor of its parent class. This is done using the super() keyword, which calls the constructor of the parent class.
  • super is used to call a superclass method: A subclass can call a method defined in its parent class using the super keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition to its own.
  • super is used to access a superclass field: A subclass can access a field defined in its parent class using the super keyword. This is useful when the subclass wants to reference the parent class’s version of a field.
  • super must be the first statement in a constructor: When calling a superclass constructor, the super() statement must be the first statement in the constructor of the subclass.
  • super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static method or a static variable initializer.
  • super is not required to call a superclass method: While it is possible to use the super keyword to call a method in the parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super keyword will invoke the parent class’s implementation.

Use of super keyword in Java

It is majorly used in the following contexts as mentioned below:
  • super can be used to refer immediate parent class instance variable.
  • super can be used to invoke immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.
Use of Super With Variables

In Java, sometimes the subclass can have a variable with the same name. The super keyword can be employed to access superclass variables. For example, if both the superclass and subclass have a variable called count, you can differentiate between them using super. Count to refer to the superclass's count variable and. Count refers to the subclass's count variable. This ensures you access the correct variable in cases of naming conflicts.

 Use of Super With Methods

When a subclass overrides a method from its superclass, you can use the super keyword to call the superclass's version of the method. This is helpful when you want to add functionality to the inherited method rather than completely replacing it. For example, if a superclass has a calculated method and a subclass wants to enhance it, you can use super.calculate() within the subclass's method to ensure that the superclass's logic is executed alongside the subclass's additions

 Use of Super With Constructors

In Java, constructors in a subclass automatically call the no-argument constructor of the superclass if not explicitly specified. However, you can use super() in a subclass constructor to call a specific constructor in the superclass. This allows you to pass arguments and initialize the superclass's state. For instance, if the superclass has a parameterized constructor, you can use super(argument) in the subclass constructor to ensure proper initialization of the superclass before initializing the subclass-specific attributes.
  • To call methods of the superclass that is overridden in the subclass.
  • To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name.
  • To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.
Note:

When we create an object of a child class, a corresponding object of the superclass is implicitly created which is referred to by the super keyword.

Even if we don't invoke the parent class constructor using super(); in the example above, the same output is generated because the child constructor implicitly calls the parent class default constructor.

Examples:

1. super with variable

This scenario occurs when a derived class and base class have the same data members. In that case, there is a possibility of ambiguity r the JVM.
// super keyword in java example

// Base class vehicle
class Vehicle {
    int maxSpeed = 120;
}

// sub class Car extending vehicle
class Car extends Vehicle {
    int maxSpeed = 180;

    void display()
    {
        // print maxSpeed of base class (vehicle)
        System.out.println("Maximum Speed: "
                        + super.maxSpeed);
    }
}

// Driver Program
class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}
/*
 *Output:
 Maximum speed: 120
 */
 
2) super with method

This is used when we want to call the parent class method. So whenever a parent and child class have the same-named methods then to resolve ambiguity we use the super keyword.

// super keyword in java example

// superclass Person
class Person {
    void message()
    {
        System.out.println("This is person class\n");
    }
}
// Subclass Student
class Student extends Person {
    void message()
    {
        System.out.println("This is student class");
    }
    // Note that display() is
    // only in Student class
    void display()
    {
        // will invoke or call current
        // class message() method
        message();

        // will invoke or call parent
        // class message() method
        super.message();
    }
}
// Driver Program
class Test {
    public static void main(String args[])
    {
        Student s = new Student();

        // calling display() of Student
        s.display();
    }
}

/*
 Output:
 This is student class
 This is person class
 */

3) super with constructor

// Java Code to show use of
// super keyword with constructor

// superclass Person
class Person {
    Person()
    {
        System.out.println("Person class Constructor");
    }
}

// subclass Student extending the Person class
class Student extends Person {
    Student()
    {
        // invoke or call parent class constructor
        super();

        System.out.println("Student class Constructor");
    }
}

// Driver Program
class Test {
    public static void main(String[] args)
    {
        Student s = new Student();
    }
}
/*
Output:
Person class constructor
Student class constructor
*/


Advantages of Using Java Super Keyword

The super keyword in Java provides many advantages in object-oriented programming are as follows:
  • Enables reuse of code: Using the super keyword allows subclasses to inherit functionality from their parent classes, which promotes the reuse of code and reduces duplication.
  • Supports polymorphism: Because subclasses can override methods and access fields from their parent classes using super, polymorphism is possible. This allows for more flexible and extensible code.
  • Provides access to parent class behaviour: Subclasses can access and use methods and fields defined in their parent classes through the super keyword, which allows them to take advantage of existing behaviour without having to reimplement it.
  • Allows for customization of behaviour: By overriding methods and using super to call the parent implementation, subclasses can customize and extend the behaviour of their parent classes.
  • Facilitates abstraction and encapsulation: The use of super promotes encapsulation and abstraction by allowing subclasses to focus on their behaviour while relying on the parent class to handle lower-level details.
  • Access to Superclass Members: It allows access to superclass variables and methods, even when overridden in a subclass, aiding in handling naming conflicts and ensuring the correct version is used.
  • Constructor Chaining: super() calls the superclass constructor, enabling proper initialization of inherited members before subclass-specific initialization, ensuring the object is in a consistent state.
  • Maintaining Inheritance: It enforces the "is-a" relationship in inheritance, promoting code reuse and extending functionality by inheriting and enhancing the behavior of parent classes.
  • Preventing Errors: Using superclarifies intentions, reducing the risk of unintentional overriding or hiding of superclass members. It helps avoid logical errors by explicitly referencing superclass members or constructors.

Important Points to Remember While Using “Java Super Keyword”

Here are some Important points that you need to take care of during using super keywords in Java:
  • Call to super() must be the first statement in the Derived(Student) Class constructor because if you think about it, it makes sense that the superclass has no knowledge of any subclass, so any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it needs to complete its execution first.
  • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, you will get a compile-time error. The object does have such a constructor, so if the Object is the only superclass, there is no problem.
  • If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that a whole chain of constructors is called, all the way back to the constructor of Object. This, in fact, is the case. It is called constructor chaining.

FAQs

  • What is super () and super keyword in Java?

Super() is a Java keyword used to call a superclass constructor. Super accesses superclass members and maintains inheritance hierarchies.

  •  What is the use of the super keyword in variables?

The super keyword in variables distinguishes superclass and subclass variables when they share the same name.

  • Why is Super important in Java?

Super is crucial in Java for accessing, initializing, and maintaining superclass-subclass relationships, enabling code reusability. 

  • Mention any three usages of the Java super keyword.
    • Access superclass members: It allows a subclass to use variables and methods from its parent class.
    • Call superclass constructors: It invokes constructors in the parent class, ensuring proper initialization.
    • Maintain inheritance relationships: Helps build a hierarchy of classes where subclasses inherit features from superclasses.
  • What is the super constructor in Java?
    • The super constructor in Java is the constructor of the superclass. It is called using the super() keyword from within the constructor of a subclass to initialize the inherited members of the superclass.
  • Can we have this() and super() together?
    •  No, it is not possible to use both this() and super() together in Java. They both refer to constructor calls and cannot be used simultaneously.
  • Which is the super class of java?
    • The Object class aka super class is at the top of the class hierarchy in Java’s java.lang package. Every class, whether predefined or user-defined, is a subclass of the Object class.

Comments