๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

"super" Keyword in Java  


Introduction
  • super keyword is a reference variable in Java.
  • It is used to refer to the immediate parent class object (i.e., the superclass of the current object).
  • This keyword is mainly used in inheritance when a subclass needs to access members (methods, constructors, or variables) of its parent class.
  • Use of super Keyword:
    1. It is used to refer the parent class instance variable.
    2. It is used to refer to the parent class method.
    3. It is used to refer to the parent class constructor.

1. It is used to refer the parent class instance variable.
  • Java Program Example 1:
    class Parent
    {
        int num = 100;
    }
    
    class Child extends Parent
    {
        int num = 200;
    
        void display()
        {
            System.out.println("Child num: " + num);
            System.out.println("Parent num: " + super.num);  // referring to parent class variable
        }
    }
    
    public class SuperDemo
    {
        public static void main(String[] args)
        {
            Child c = new Child();
            c.display();
        }
    }

2. It is used to refer to the parent class method.
  • Java Program Example:
    public class ThisDemo
    {
        void showMessage()
        {
            System.out.println("Hello from showMessage() method");
        }
    
        void display()
        {
            // Calling another method of the same class using 'this'
            this.showMessage();  // Optional: can also call showMessage() directly
            System.out.println("Inside display() method");
        }
    
        public static void main(String[] args)
        {
            ThisDemo obj = new ThisDemo();
            obj.display();
        }
    }

3. It is used to refer to the parent class constructor.
  • Java Program Example:
    package notesprogram;
    
    class Parent
    {
        Parent()
        {
            System.out.println("Parent constructor called");
        }
    }
    
    class Child extends Parent
    {
        Child()
        {
            super(); // calls Parent's constructor
            System.out.println("Child constructor called");
        }
    }
    
    public class SuperDemo
    {
        public static void main(String[] args)
        {
            Child c = new Child();
        }
    }
    • Note : super() must be the first statement in a constructor
      • If used, the call to the parent class constructor (super()) must appear as the very first statement in the child class constructor.