When to Use the "super" Keyword in Java

Answered using GPT-4o-mini by Java Q&A Hub

Question:

When can you use the "super" keyword In Java?

Answer:

In Java, the super keyword is used in several contexts, primarily to refer to the superclass of the current object. Here are the main scenarios where you can use the super keyword:

  1. Accessing Superclass Methods: You can use super to call a method from the superclass that has been overridden in the subclass. This is useful when you want to invoke the superclass's version of the method.

    class Parent {
        void display() {
            System.out.println("Parent display");
        }
    }
    
    class Child extends Parent {
        void display() {
            super.display(); // Calls the Parent's display method
            System.out.println("Child display");
        }
    }
    
  2. Accessing Superclass Constructors: You can use super() to call a constructor of the superclass from the subclass constructor. This must be the first statement in the subclass constructor.

    class Parent {
        Parent() {
            System.out.println("Parent constructor");
        }
    }
    
    class Child extends Parent {
        Child() {
            super(); // Calls the Parent's constructor
            System.out.println("Child constructor");
        }
    }
    
  3. Accessing Superclass Fields: If a subclass has a field with the same name as a field in its superclass, you can use super to refer to the superclass's field.

    class Parent {
        int value = 10;
    }
    
    class Child extends Parent {
        int value = 20;
    
        void display() {
            System.out.println("Child value: " + value); // Refers to Child's value
            System.out.println("Parent value: " + super.value); // Refers to Parent's value
        }
    }
    

Summary

  • Use super.methodName() to call a method from the superclass.
  • Use super() to call a superclass constructor.
  • Use super.fieldName to access a field from the superclass when there is a naming conflict.

These usages help in managing inheritance and ensuring that the correct methods and fields are accessed in a class hierarchy.