|
The super keyword
The super keyword is used within a class to refer to it's parent class.
For example, if "Student" class extends a generic class "Human", then within Student, the super keyword would provide a reference to Human.
Pseudo code for above example is shown below:
class Human{
String name;
public String getName(){
return name;
}
public void disp(){
System.out.println("Human");
}
} // end class Human
class Student extends Human{
int rollNo;
int getRollNo{
return rollNo;
}
public void disp(){
System.out.println("Student");
}
public void dispHuman(){
super.disp(); // This calls Human.disp()
}
public static void main(){
Student s = new Student();
s.disp(); // This would print "Student"
s.dispHuman(); // This would print "Human"
}
} // end class Student
Another important usage of super keyword is to call parent class' constructor; i.e. placing super() in a class' constructor, would call parent's constructor. This would ensure that whenever a child class gets instantiated, all the steps written in it's parent's constructor are executed.
super( ) must always be the first statement executed inside a subclass’ constructor.
|