Java

super Keyword

Java / super Keyword

super Keyword

super Keyword

The super keyword in Java is used to refer to the parent class (superclass) from a child class (subclass). It is mainly used to access parent class variables, methods, and constructors. It helps to remove confusion when both parent and child class have the same method or variable names.

The super keyword is used in two main ways:

  • To access attributes and methods of the parent class
  • To call the parent class constructor

Example

class Parent {

Β  Β int x = 10;

Β  Β // Parent class method
Β  Β void show() {
Β  Β  Β  Β System.out.println("This is Parent class method");
Β  Β }
}

class Child extends Parent {

Β  Β int x = 20;

Β  Β void display() {

Β  Β  Β  Β // Access child class variable
Β  Β  Β  Β System.out.println("Child class x = " + x);

Β  Β  Β  Β // Access parent class variable using super
Β  Β  Β  Β System.out.println("Parent class x = " + super.x);

Β  Β  Β  Β // Call parent class method using super
Β  Β  Β  Β super.show();
Β  Β }
}

public class Main {
Β  Β public static void main(String[] args) {

Β  Β  Β  Β // Creating object of Child class
Β  Β  Β  Β Child obj = new Child();

Β  Β  Β  Β // Calling child class method
Β  Β  Β  Β obj.display();
Β  Β }
}

Technology
Java
want to connect with us ?
Contact Us