Thursday, 8 March 2012

super keyword in Java

•What is the use of super keyword in Java?
•Suppose the superclass wants to restrict access to its instance variables by declaring them as “priavte”.
•Also you might want to pass some parameters to the superclass constructor to initialize its instance variables.
•Also when you declare variables with same name in both superclass and subclass, there is need to distinguish both of them.
•For these reasons Java provides a keyword called “super”.

•super can be used in two ways:
1) To invoke the immediate superclass constructor from the subclass constructor.
2) To refer the immediate superclass members from the subclass.

When invoking the superclass constructor using the super keyword, it must be the first line in the body of the subclass constructor.

Using super to invoke superclass constructor:




•In the previous program if we create a object for the SubClass as shown below:
SubClass obj = new SubClass(10,20,30,40);
•The constructor in the SubClass will be invoked, which in turn invokes the SuperClass constructor and passes the values 10,20 and 30 to it.
•So the values of the variables will be like this:
a = 10, b = 20, c = 30, d = 40


Using super to refer the superclass members:

•The second use of super keyword is to refer the members of immediate superclass.
•There will be some situations in which the members of both the superclass and subclass has the same name.
•In such case, to refer/access the superclass members in the subclass, we will use the super keyword.
Lets look at a sample program…



2 comments: