Java super keyword

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
Example
super.number; //number of super class is accessed
3. The ‘super’ can be used to invoke super class constructor
Example
super(“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 example
public 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();
    }
}

Java method overloading and overriding
Java method overloading and overriding - Define Method overloading, Uses of method overloading, uses of method overriding, Difference between overloading and overriding...
Java string class
Java string class - Describe Java string class. Explain methods of Java string class. Explain the characteristics of StringBuffer class.....
Java inner classes
Java inner classes - What is Java inner class? Explain the types of inner classes, i.e. Static member classes, Member classes, Local classes, Anonymous classes, Functionality of wrapper classes. List the primitive types and the corresponding wrapper classes...
Post your comment