2011-12-10

Use of super keyword in java ?

The super is a java keyword,used to access the members of the super class.Use of keyword super is to access the hidden data variables of the super class hidden by subclass.
Ex:Suppose Example class is the super class in the below program that has two instance variables as int x and int y. Sample class is the subclass that also contains its own data members named x and y,then we can access the super class (Example class) variables x and y inside the subclass (Sample class) just by calling the following command.
super.member;
Here member can either be an instance variable or a method. super keyword most useful to handle situations where the local members of the subclass hide the members of the super class having the same name.

Hence super keyword can be defined as "it's a non static variable used to store super class non-static memory reference through current sub class object."

//Example.java
class Example
{
   int x=10;
   int y=20;
   void m1(){
      System.out.println("Example m1");
   }
}

//Sample.java
class Sample extends Example
{
   void m2(){
      System.out.println("x: "+x);
      System.out.println("y: "+y);
   }
   public static void main(String[] args)
   {
      Sample s = new Sample();
      s.m2();
   }
}

Output:

  x: 10
  y: 20

In the above program compiler first checks if the variables are available in that method or not which is nothing but local preference if they are available then they are accessed from that method itself if they are not available then compiler replaces x and y variables by this.x and this.y to check variables are present at sub class level, if the variables are not available in sub class they are replaced by super.x and super.y to access those variables if they are present in super class. This is the internal mechanism done by compiler. "this" and "super" keyword is placed implicitly. But if you want to place those keywords explicitly then check below program.

//Example.java
class Example
{
   int x=50;
   int y=60;
   void m1(){
      System.out.println("Example m1");
   }
}

//Sample.java
class Sample extends Example
{
   int x=30;//class level variables
   int y=40;

   void m2(){
      int x=10;//loacal preference 
      int y=20;

      System.out.println("x: "+x);
      System.out.println("y: "+y);
      System.out.println();
      System.out.println("x: "+this.x);
      System.out.println("y: "+this.y);
      System.out.println();
      System.out.println("x: "+super.x);
      System.out.println("y: "+super.y);
    }

   public static void main(String[] args){
      Sample s = new Sample();
      s.m2();
   }
}

Output:

  x: 10
  y: 20

  x: 30
  y: 40

  x: 50
  y: 60

Loading

Enter your Email here: