super keyword in java
The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.Usage of super Keyword
super can be used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.Example
File: TestSuper.javaclass Person { String name = "sanjay"; } class Child extends Person { String name = "rajkumar"; void printname() { System.out.println(name); //prints name of Child class System.out.println(super.name); //prints name of Person class } } class TestSuper{ public static void main(String args[]) { Child c = new Child(); c.printname(); } }
Output:
rajkumar sanjay
super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.Example:
File: TestSuper1.javaclass Person { void eat() { System.out.println("eating moment"); } } class Child extends Person { void eat() { System.out.println("eating with milk"); } void laugh() { System.out.println("laughing moment); } void work() { super.eat(); laugh(); } } class TestSuper1 { public static void main(String args[]) { Child c = new Child(); c.work(); } }
Output:
eating moment laughing moment
super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor.Example:
File: TestSuper2.javaclass Person { Person() { System.out.println("person can run"); } } class Child extends Person { Child() { super(); System.out.println("child can walks"); } } class TestSuper2 { public static void main(String args[]){ Child c = new Child(); }}
Output:
person can run child can walks
super example: real use
see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.Example:
File: TestSuper3.javaclass Person { int id; String name; Person(int id,String name) { this.id=id; this.name=name; } } class Servant extends Person{ float salary; Servant(int id,String name,float salary) { super(id,name); //reusing parent constructor this.salary = salary; } void display() { System.out.println(id+" "+name+" "+salary); } } class TestSuper3{ public static void main(String[] args) { Servant s = new Servant(109,"rajkumar",80000f); s.display(); } }
Output:
109 rajkumar 80000