Super Keyword
refers to the objects of immediate parent class. Before learning super keyword you must have the knowledge of inheritance in Java
The use of super keyword
1) To access the data members
of parent class when both parent and child class have member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class
3) To access the method of parent class when child class has overridden that method.
Example: of super keyword
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are
* writing super.num in the print statement
* this refers to the num variable of Superclass
*/
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Example of super keyword to invoke constructor of parent class
class Parentclass
{
Parentclass(){
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* Compile implicitly adds super() here as the
* first statement of this constructor.
*/
System.out.println("Constructor of child class");
}
Subclass(int num){
/* Even though it is a parameterized constructor.
* The compiler still adds the no-arg super() here
*/
System.out.println("arg constructor of child class");
}
void display(){
System.out.println("Hello!");
}
public static void main(String args[]){
/* Creating object using default constructor. This
* will invoke child class constructor, which will
* invoke parent class constructor
*/
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
/* Creating second object using arg constructor
* it will invoke arg constructor of child class which will
* invoke no-arg constructor of parent class automatically
*/
Subclass obj2= new Subclass(10);
obj2.display();
}
}