super keyword

Email this to someonePrint this pageShare on Google+2Share on Facebook0Tweet about this on TwitterShare on LinkedIn1Share on Reddit0Pin on Pinterest0Share on StumbleUpon1


super keyword
The super keyword is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of super Keyword

  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance variable.

Problem without super keyword

In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.

Solution by super keyword

2) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as given below:

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

defsuper

As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don’t have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.

Another example of super keyword where super() is provided by the compiler implicitly.

3) super can be used to invoke parent class method.

The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:

In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.

Program in case super is not required

Email this to someonePrint this pageShare on Google+2Share on Facebook0Tweet about this on TwitterShare on LinkedIn1Share on Reddit0Pin on Pinterest0Share on StumbleUpon1

About Team

Browse Archived Articles by Team

  • anurag srivastav

    good job