๐Ÿ”ฅ Lohri โ€ข ๐Ÿช Makar Sankranti โ€ข ๐Ÿ‡ฎ๐Ÿ‡ณ Republic Day | Offers | Upto 70% OFF + Extra 26% OFF โ€” One Coupon for All Courses โ†’ BHARAT26 ( Limited Period Celebration Offer ) << Explore Professional Courses >>

"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:
    class Parent
    {
        void showMessage()
        {
            System.out.println("Hello from Parent class showMessage() method");
        }
    }
    
    class Child extends Parent
    {
        void display()
        {
            // Calling parent class method using 'super'
            super.showMessage();
            System.out.println("Inside Child class display() method");
        }
    }
    public class SuperDemo
    {
        public static void main(String[] args)
        {
            Child obj = new Child();
            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.