Super Keyword in Java Simplified:
- Super class’s instance variables
- Super class’s methods
- Super class’s Constructors
Super class’s methods:
If super class does not have a method called soSomething()(addition in child rather than modification), the compiler will throw an syntax error.
If we have a method defined in a super class and a sub class extends the super class, then the sub class inherits the method by the rule of inheritance and it can be used by the object created from sub class.Method inheritance enables us to define and use methods repeatedly in subclasses without defining it again. Now if the object wants to respond to the same method in a different way(different from parent’s class method),we need to override the method definition(defined in super class).When the method is called the redefined method in child class gets executed instead of the method defined in Super class.
class Super{
//variable decleration
int x;
Super(int x){this.x=x;}
//method definitaion
void display(){
System.out.println("Super x "+x);
}
}
class Sub extends Super{
int y;
Sub(int x,int y){
super(x);
this.y=y;}
void display(){
System.out.println("Sub x "+x);
System.out.println("Sub y "+y);
}
}
public class SuperTest{
public static void main(String[] args)
{
Sub sb=new Sub(10,20);
sb.display();
}
}
output of the code:
$javac SuperTest.java
$java -Xmx128M -Xms16M SuperTest
Sub x 10
Sub y 20
Advantages of Super keyword:
- We can access to things in the super class that are hidden by things in the sub classes. Suppose we say Super.X it signifies to an instance variable named x defined in Super class.
- If a class contains an instance variable with the same name as an instance variable in the super class,then an object of that class will actually contains two variables with the same name. One defined as part of the class itself and one defined as part of the super class.The variable defined in the sub class does not replace the variable of the same name defined in the super class.The variable from super can still be accessed with the keyword called super.
- If we write a method in a subclass that has the same signature and name as of super class,the method from super class is hidden in the same way.We say that the method in the subclass overrides the method from the super class. Using super keyword we can still access and work with the super class method.
- Re usability of code is the major advantage of super keyword. The major use of super is to overrides a method with new method that extends the behavior of the inherited method,instead replacing the behavior completely.The new method can use super to call the method from super class and then it can add additional functionalities.