Friday 20 March 2015

The super keyword in Java

This article explains the usage of super keyword with simple example.

    The super keyword in java is an instance variable or method that is used to refer immediate parent class object.

Syntax:
super.member;

Lets discuss with an example:


Output:






1)In the superclass and subclass we have declared a variable a and b .
2)Both the class consists the method PrintMethod() .
3)We have created an object of subclass .
4)Here our intention is to print the variables which are in both super and subclass and need to call the method of super class.
5) From the above logic we cannot print the superclass variables and call the super class method.

If you see the output it printed only the variables in the subclass.
Using super keyword we can call the instance variable or method of super class . See the below example.


Output:







Here we have printed the super class instance variables and methods.
Another usage of super() is to invoke immediate parent class constructor. We will discuss this later.




                                                                                  

No comments: