Sunday, 10 July 2016

"super" keyword in java

The super keyword is a reference variable that is used to refer immediate parent class object. Whenever we create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
class Parent { 
     String classN = "Parent"
}
class TestSuper extends Parent { 
     String classN = "Child";
     void display() {
           System.out.println(classN);
           System.out.println(super.classN); 
     } 
     public static void main(String args[]) { 
           TestSuper ts=new TestSuper(); 
           ts.display();
     } 
}
Output:
Child
Parent

2. super can be used to invoke parent class constructor.
class Parent {
     public Parent(String str) {
           System.out.println(str);
     }

class TestSuper extends Parent { 

     TestSuper() { 
           super("call parent");//will invoke parent class constructor 
           System.out.println("Child"); 
     } 

     public static void main(String args[]) { 
           TestSuper ts=new TestSuper(); 
     } 
}

3. super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method.
class Parent { 
     public void method() {
           System.out.println("Parent class");
     }
}
class TestSuper extends Parent { 
     public void method() {
           System.out.println("Child class");
     }
     public void display() {
           method();
           super.method();
     }
     public static void main(String args[]) { 
           TestSuper ts=new TestSuper(); 
           ts.display();
     } 
}

Note:
1. super() is added in each class constructor automatically by compiler.

super() is provided by the compiler implicitly:
class Parent { 
     public Parent() {
           System.out.println("Parent");
     }

class TestSuper extends Parent { 

     TestSuper() {
           System.out.println("Child"); 
     } 

     public static void main(String args[]) { 
           TestSuper ts=new TestSuper(); 
     } 
}

2. No need of super keyword to call parent class method:
If there is no method in subclass as parent, there is no need to use super.

class Parent { 
     public void method() {
           System.out.println("Parent class");
     }

class TestSuper extends Parent { 
     public void display() {
           method();
     }

     public static void main(String args[]) { 
           TestSuper ts=new TestSuper(); 
           ts.display();
     } 
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...