Whenever a member in the superclass is declared as private member it is not available for use by the subclass. The java provides a solution to this problem also.
When a subclass needs to refer to its immediate super class, it can do the use of keyword super.The keyword super is used in the following cases.
(1) To call super class constructor.
(2) To refer the instance variable of Super class which is hidden by subclass.
The above three cases are explained as follow:
(1) To call super class constructor
A Subclass constructor is used to construct the instance variables of both the subclass and the superclass. The subclass constructor uses the keyword super to invoke the constructor method of the superclass.
The subclass can call a constructor defined by its superclass by the use of following form of super.
super (parameter-list);
Where parameter-list specifies any parameters needed by the constructor in the super class.
Consider following necessary points while use a super to call a constructor of superclass.
- Super may only be used within a subclass constructor method.
- The call to superclass constructor must appear as the first statement within the sub class constructor.
- The parameters in the super call must match the order and type of the instance variable declared in the superclass.
super is useful when one or more member names of the subclass hides members of the superclass. It means that the subclass has the same member name as superclass.So here the subclass hides the instance member of the superclass. The keyword super is also using to refer the superclass version of the member. It can call a memeber of superclass by following form.
super.member
Here, the member can be any instance method or variable.super is also used to call overridden method of super class.
Posted by: Ruchita Pandya
Super keyword in java
ReplyDeleteOh, nice post