The super keyword is a reference variablethat is used to refer immediate parent class object. Whenever we create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
class Parent {
String classN = "Parent";
}
class TestSuper extends Parent {
String classN = "Child";
void display() {
System.out.println(classN);
System.out.println(super.classN);
}
public static void main(String args[]) {
TestSuper ts=new TestSuper();
ts.display();
}
}
Output:
Child
Parent
2. super can be used to invoke parent class constructor.
class Parent {
publicParent(String str) {
System.out.println(str);
}
}
class TestSuper extends Parent {
TestSuper() {
super("call parent");//will invoke parent class constructor
System.out.println("Child");
}
public static void main(String args[]) {
TestSuper ts=new TestSuper();
}
}
3. super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method.
class Parent {
public voidmethod() {
System.out.println("Parent class");
}
}
class TestSuper extends Parent {
public voidmethod() {
System.out.println("Child class");
}
public voiddisplay() {
method();
super.method();
}
public static void main(String args[]) {
TestSuper ts=newTestSuper();
ts.display();
}
}
Note:
1. super() is added in each class constructor automatically by compiler.
super() is provided by the compiler implicitly:
class Parent {
public Parent() {
System.out.println("Parent");
}
}
class TestSuper extends Parent {
TestSuper() {
System.out.println("Child");
}
public static void main(String args[]) {
TestSuper ts=new TestSuper();
}
}
2. No need of super keyword to call parent class method:
If there is no method in subclass as parent, there is no need to use super.
class Parent {
public void method() {
System.out.println("Parent class");
}
}
class TestSuper extends Parent {
public void display() {
method();
}
public static void main(String args[]) {
TestSuper ts=new TestSuper();
ts.display();
}
}
No comments:
Post a Comment