Super Keyword in Java

Super Keyword in Java

Super allude to the parent class. It holds the reference id of

the parent segment of youngster class object. See beneath model.

class A
{
                int
x=10;
}
class B extends A
{
                int
x=20;
}
Super Keyword in Java

Here you can see that in youngster object, two separate segments

are made to be a specific parent area and kid segment. So super really allude to parent area.

Utilization of Super Keyword in Java

There is three utilization of super keyword in java.

  • Access parent class occasion variable.
  • Conjure parent class strategy.
  • Summon parent class constructor.

Beneath program will show all the three utilization of super keyword.

class parent
{
                int x=20;              
                parent()
                {
                                System.out.println("Parent");
                }
 
                void show()
                {
                                System.out.println("Parent Show");
                }
}
 
class child extends parent
{
                int x=30;
 
                child()
                {
                                super();                                //invoke parent constructor
                }
 
                void show()
                {
                                System.out.println("Child Show");
                }
 
                void display()
                {
                                System.out.println(x);                   //print child x
                                System.out.println(super.x);      //print parent x
 
                                show();                                //invoke child show()
                                super.show();   //invoke parent show()
                }
 
                public static void main(String...s)
                {
                                child c=new child();
                                c.display();
                }
} 

Output

Super Keyword in Java
  • Here both the classes have variable x and technique appear(). To get to a variable of kid class we basically compose x and to get to a variable of parent class we compose super.x.
  • Likewise, to conjure strategy for the kid we straightforward compose appear() and to conjure technique for a parent we compose super.show(). Along these lines super is likewise used to evacuate the issue of strategy abrogating.
  • super() must be the first line of the constructor. In the above model, we have composed super() in the first line of youngster class constructor to call parent class constructor.
  • Super can’t be utilized in static technique. Of course, super is the first line of constructor. Super keyword also, this keyword can’t be utilized together in the constructor.

Leave a Comment