Home Help Java S Super keyword in java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Super keyword in java

Advertisement
In this section we will discuss about the super keyword in java. Super is a keyword defined in java. Super is used to refer the variable, methods and constructor of the super or parent class.

Super keyword in java

In this section we will discuss about the super keyword in java. Super is a keyword defined in java. Super is used to refer the variable, methods and constructor of the super or parent class. If we override one of the super class method ,then we can invoke the super class method using "super" keyword. Here is the example to use super to call super class methods.

    class superclass
    {
     public void demo()
      {
      System.out.println("In super class");
      }
   }

Now, Here is a subclass that override demo() method.

   public class subclass extends superclass
   {
      public void demo()
      {
       super.demo();  //override demo method in superclass
       System.out.println("In sub class ");
      }
      public static void main(String args[])
       {
        Subclass sb=new Subclass();
        sb.demo();
       } 
    }  

So, to refer the demo() method in the superclass super is used in the subclass and the output will be the following.

In super class

In sub class

Super is also used to call super class constructor, default constructor is called by super() with no args and parameterized constructors super(parameter) with arguments. The following example illustrate how to use super to call superclass constructors.

class superclass
 {
     superclass()
     {
	  System.out.println("In superclass constructor");
     }
     
   }
     public class Subclass extends superclass
     {
    	 Subclass()
    	 {
    		 super();  //calling superclass constructor
    		 System.out.println("In sub class constructor");
    	 }
        
    	 public static void main(String args[])
       {
        Subclass sb=new Subclass();
      
        } 
     }  

Output :  After compiling and executing output will be as follows:

In superclass constructor

In sub class constructor

Note : While calling super class constructor in sub class, super() should be the first statement. super() with no args is automatically created by compiler while object creation.

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 16, 2013

Ask Questions?    Discuss: Super keyword in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com