Explain the importance of 'super' keyword in Java. Write code to depict the uses of 'super' keyword.
1. The keyword ‘super’ is used for referring parent class instance
2. Same data members of super class hides the variables by the sub class
Examplesuper.number; //number of super class is accessed
3. The ‘super’ can be used to invoke super class constructor
Examplesuper(“Bangalore”); //the string “Bangalore” is sent to super class constructor
4. The ‘super’ can be used to invoke super class method with the same name of the current class
Example super.showResult();
Code examplepublic class Superclass
{
public void printMethod()
{
System.out.println("Printed in Superclass.");
}
}
Subclass that overrides the method printMethod():
public class Subclass extends Superclass
{
public void printMethod()
{
//overrides printMethod in Superclass
super.printMethod(); // invokes the super class’s printMethod()
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{
Subclass sub = new Subclass();
sub.printMethod();
}
}