Saturday, 18 March 2017

'super' Keyword

Lets discuss about one of the interesting and widely used keyword 'super'.super keyword is used to access the properties of the parent class.

super with respect to variables:

We use super keyword when we want to access the variables of the immediate parent class.

Example:

class Parent
{
 int a=5;
}
class Child extends Parent
{
 int a=10;
 void printvalue()
 {
  System.out.println("Child class variable is "+a);  //Child class member
  System.out.println("Parent class variable is "+super.a);  //Parent class member
 }
}
class Mainclass 
{
 public static void main(String []args)
 { 
  Child c=new Child();
  c.printvalue();
 }
}
Output:
Child class variable is 10
Parent class variable is 5
Here if we do not use super the value of a is '10'(child class) if we use super the value initialized in the parent class is assigned to a.



Super with respect to methods:

Super keyword is used to invoke the methods in the immediate parent class.It is especially used incase of method overriding.
class Parent
{
 int i=10;
 void message()
 {
  System.out.println("parent class variable "+i);
 }
}
class Child extends Parent
{
 int i=5;
 void message()
 {
  super.message();
  System.out.println("child class variable"+i);
 }
}
class Mainclass
{
 public static void main(String []args)
 {
  Child c=new Child();
  c.message();
 }
}
Output:
parent class variable is 10.
child class variable is 5.

Super with respect to constructors:

As we all know,constructors are primarily known for initializing the variables.To invoke a parent class constructor,the super must be placed in the first line of the Child class constructor.
class Parent
{
 int i;
 Parent(int b)
 {
  i=b;
 }
}
class Child extends Parent
{
 int i;
 Child(int a,int b)
 {
  super(b);
  i=a;
 }
 void show()
 { 
  System.out.println("child class variable "+i);
  System.out.println("parent class variable"+super.i);
 }
}
class Mainclass
{
 public static void main(String []args)
 {
  Child c=new Child(5,10);
  c.show();
 }
}
Output:
child class variable 5
parent class variable 10 

Note:

In the case of constructors,if the child class does not explicity invoke a parent class constructor,the compiler automatically inserts a call to the no argument constructor of the parent class.If the parent class does not have a no-argument constructor,you will end up with a compilation error.

No comments:

Post a Comment