0
0
Javaprogramming~5 mins

Super keyword in Java

Choose your learning style9 modes available
Introduction

The super keyword helps you access methods and variables from a parent class. It is useful when you want to use or extend the behavior of the parent class.

When you want to call a parent class constructor from a child class.
When you want to access a parent class method that is overridden in the child class.
When you want to access a parent class variable that is hidden by a child class variable.
Syntax
Java
super.methodName();
super.variableName;
super();  // calls parent class constructor

super() must be the first statement in a child class constructor if used.

You can use super to avoid confusion when child and parent have variables or methods with the same name.

Examples
This example shows how super calls the parent method and accesses the parent variable.
Java
class Parent {
    int x = 10;
    void show() {
        System.out.println("Parent show");
    }
}

class Child extends Parent {
    int x = 20;
    void show() {
        System.out.println("Child show");
        super.show();  // calls Parent's show
        System.out.println(super.x);  // accesses Parent's x
    }
}
This example shows how super() calls the parent constructor from the child constructor.
Java
class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super();  // calls Parent constructor
        System.out.println("Child constructor");
    }
}
Sample Program

This program shows how the child class uses super to access the parent class variable and method even when they are overridden or hidden.

Java
class Parent {
    int number = 100;
    void display() {
        System.out.println("Parent display: " + number);
    }
}

class Child extends Parent {
    int number = 200;
    void display() {
        System.out.println("Child display: " + number);
        System.out.println("Parent number using super: " + super.number);
        super.display();
    }
}

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.display();
    }
}
OutputSuccess
Important Notes

If you do not use super() in a child constructor, Java automatically calls the parent's no-argument constructor.

You cannot use super in static methods because super refers to instance members.

Summary

super helps access parent class methods and variables.

Use super() to call the parent constructor from a child constructor.

It is useful when child class overrides or hides parent class members.