^

Super Keyword

The super keyword always refers to the base class of the class in which the keyword super is used
Basically keyword super is a reference variable used to refer immediate parent class object. Whenever you create object of a subclass, an object of parent class is created implicitly. Only instance methods and constructors can use this keyword.
The keyword super can be used in the following situations
  1. To refer instance variable of immediate parent class.
  2. To invoke methods of immediate parent class.
  3. To invoke constructors of parent class from constructor of derived class.
It is similar to keyword this. However, this keyword is used to refer instance variables, methods and constructors of the object to which it refers currently.
  1. Using super to refer instance variables of immediate parent class:
  2. When the base and derived classes consist of variables having identical names, then the methods of derived class use super to make them diff erentiate, as shown in the program below:
    class CarLoan
       {
    	float rate = 10.10f;
       }	
    class HomeLoan extends CarLoan
       {
    	     float rate = 12.12f;
        void showRates()
    	 {
    	    System.out.println(“Carloan Rate = “ + super.rate);	//10.10
    	    System.out.println(“Home loan Rate = “ + rate);	// 12.12
    	 }  
       }
    class Ldemo
       {
           public static void main(String args[])
       	  {
    		HomeLoan HL = new HomeLoan();
    		HL.showRates();
    	  }
      } 
    
  3. Using super to invoke methods of immediate parent class:
  4. Keyword super can also be used to invoke the methods of immediate base class. Generally, it is used to call overridden methods of the base class from the derived class. Consider the following sample code:
    class B
       {	void fun()
    	   {
    		System.out.println(“method of Base class”);
    	   }  
        }
    class D extends B
        {
    	void fun()
    	   {
    		System.out.println(“method of Derived Class”);
    	   }
        }
    
    If you create object of class D and call fun() method,fun() of class D will be called.Consider the following code:
    real java super keyword
    But if you want to call fun() method of classB, use keywordsuper in fun() method of derived class D, as shown below:
     class D extends B
       {	void fun()
    	   {
    		System.out.println(“method of Derived class”);
    		super.fun();	// Calling fun() of class B
    	   }
       }
  5. Using super to invoke constructor of immediate base class:
  6. Whenever the base class and derived class consist of default constructors, then on instantiation of derived class, the constructor of base class executes before the constructor of derived class. In other words, constructors executes from top to bottom, as shown below:
    Case-A: When base and derived classes consist of default constructors:
    real java super invoke constructor
    Implementation:
    The following program demonstrates the top to bottom execution of default constructors:
    class Base
       {	Base()	  //1
    	   {System.out.println(“Base class Constructor”);
    	   }
       }
       class Derived extends Base
       {
    	Derived()	     //2
    	   {
    		System.out.println(“Derived Class Constructor”);
    	   }
       }
    class CIDemo
       {
    	public static void main(String args[])
    	   {
    		Derived d = new Derived();
    	   }
       }
    Output:
    Base Class Constructor
    Derived Class Constructor
    Explanation
    In this program, when the class Derived is instantiated in line number-17, then control goes first to the constructor of class Derived, and then it is forwarded to constructor of class Base for execution of its default constructor. After execution of Base()constructor, control comes back to Derived()constructor.
    Why constructor of base class executes first?
    Generally a question arises, why constructor of super class executes first? The reason is simple: sometimes derived class constructor use variables of base class, which are initialized by constructor of base class and used by constructor of derived. So to provide accurate data to assist the working of sub class constructors, constructor of base class executes first.
    Implementation:
    For better understanding of this concept consider the following program. This program consist of a class Data having default constructor which initializes the PI variable to be used by the methods of derived class Circle for calculating area of circle.
    class Data
       {
    	float PI;
    	Data()
    	  {
    		PI = 3.14f;
    	  }
        }
    class  Circle extends Data
        {
    	float Ar;
    	Circle()
    	   {
    		Ar = PI * 10 * 10;
    		System.out.println(“Area of Circle: “ + Ar);
    	   }
        }
    class CDemo
       {
    	public static void main(String args[])
    	   {
    		Circle c = new Circle();
    	   }
       }
    
    Output: Area of Circle : 314 
    Explanation
    In this program, the constructor of base class Data executes before the constructor of derived class Circle which initializes to fl oat value 3.14.Then the constructor of derived class uses the PIvariable to calculate the area of circle.
Case-B: When base and derived classes consist of parameterized constructors
In case-1, you came to know that the default constructor of derived class implicitly invokes the default constructor of immediate base class without using keyword super.
If base and derived classes consist of parameterized constructors, then the default constructor and parameterized constructor of derived class invoke default constructor of base class implicitly. But if you want to invoke parameterized constructor of base class from either default constructor or parameterized constructor, then keyword super is used. Remember, the statement consisting super must be the first statement within constructor.
For example, in the following program, the parameterized constructor of derived class (SavingAccount) invokes parameterized constructor of base class (Account) using keyword super.
class Account
  {   String accNo;
	   Account()	//default constructor
	      {      }		     	 
	   Account(String Ac)	// parameterized constructor
	      {     accNo = Ac;
     	      }
  }
class SavingAccount extends Account
  {  float bal;
	 SavingAccount() 	//default constructor
	        {	    }
	SavingAccount(float b, String acc)  //parameterized constructor
	       {
		 super(acc);  //calling parameterized const. using super 
		bal = b;
	       }
	void show()
	      {	System.out.println(“AccountNumber : ” + accNo);
		System.out.println(“Balance : “ + bal);
	     }
  }
class PCDemo
  {	
	public static void main(String args[])
	   {   SavingAccount sa = new SavingAccount(7000, “SA786”);
	        sa.show();
	   }
  }
Output: Account Number : SA786
Balance: 7000
Explanation
In this program, parameterized constructor (line number 13) is invoked on instantiation of SavingAccount class (see line number-26). In line number-15, super(acc) invokes parameterized constructor of Account class (line number 5). After executing line number-6, control goes back to line number-16 to initialize bal variable of class SavingAccount.If we use super() instead of super(acc) then it calls default constructor of base class instead of parameterized constructor.

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap