Super Keyword in Java or program to demonstrate usage of super keyword. rcub

 

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class object.


Usage of Java super Keyword

-->super can be used to refer immediate parent class instance variable.

--> super can be used to invoke immediate parent class method.

--> super() can be used to invoke immediate parent class constructor.


1.super can be used to access Base class Variables.

Syntax: super.<instance variable>;


Example:
class A
{
      int a;
}
class B extends A

        B(int x)
       {
           super.a=x;
         }
     void display() 
   {
     System.out.println("A value="+super.a);
   }
  public static void main(String args[])
  {
       B o=new B(5);
      o.display();
     }


Output:
A value =5


2.super can be used to invoke immediate parent class method.

Syntax:
super.<method-name>(arguments if any) ;


Example:
class A
{
     int a;
    void show()
     {
      System.out.println("A value="+a);
      }
}
class B extends A

       int b;
      B(int x, int y)
     {
       super.a=x;
         b=y;
      }
     void display()
    { 
      super.show();
       System.out.println("B value="+b);
     }
    public static void main(String args[])
   {
     B o=new B(5, 10);
    o.display();
  }
}

Output:
A value=5
B value=10


3.super() can be used to invoke immediate parent class constructor.


Syntax:
<derived class constructor>
{
     super(<argument-list>);
}

Example:
class A
{
     int a;
    A()
     {
      System.out.println("constructor     invoked");
      }
}
class B extends A
{     
       int b;
      B(int x, int y)
     {
        super();
        super.a=x;
         b=y;
      }
     void display()
    { 
System.out.println("A value="+a);
System.out.println("B value="+b);
    }
    public static void main(String args[])
   {
     B o=new B(5, 10);
    o.display();
  }
}


Output:
Constructor invoked.
A value=5
B value=10


Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Abstract classes and Abstract methods in Java with Examples rcub.

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.