Pages

Wednesday, February 11, 2015

Super Keyword in Java

Super refer to parent class. It holds the reference id of parent section of child class object. Observe below example.

class A
{
                int x=10;
}

class B extends A
{
                int x=20;

}

Super Keyword in Java

Here you can see that in child object, two separate sections are created namely parent section and child section. So super actually refer to parent section.

Use of Super Keyword in Java

There are three usage of super keyword in java.
  • Access parent class instance variable.
  • Invoke parent class method.
  • Invoke parent class constructor.


Below program will show all the three usage 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();
}
}
           
Super Keyword in Java - Output

  • Here both the classes have variable x and method show(). To access variable of child class we simply write x and to access variable of parent class we write super.x.
  • Similarly, to invoke method of child we simple write show() and to invoke method of parent we write super.show(). In this way super is also used to remove the problem of method overriding.
  • super() must be first line of the constructor. In above example we have written super() in first line of child class constructor to call parent class constructor.
  • Super can’t be used in static method.
  • By default super is first line of constructor. Super keyword and this keyword can’t be used together in constructor.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.