Super Keyword in Java

Super Keyword in Java#

super keyword is used for many cases in java

  • Super keyword can be used to use field or datamember of parent class
  • Super keyword can be used to invoke parent class method
  • super keyword can be used to invoke immediate parent class constructor

Super keyword can be used to use field or datamember of parent class

If we have a same named data member or field in the parent class and child class,then use super with the data member name inside the child class,to access the datamember present in the parent class

class student{
String gender="male";
}
class girl extends student{
String gender="female";
void show(){
System.out.println("girl class gender is "+gender);
System.out.println("student class gender is "+super.gender);
}
}
class main11{
public static void main(String[] args){
girl obj=new girl();
obj.show();
}
}

Output

girl class gender is female
student class gender is male

Super keyword can be used to invoke parent class method

If we have a same-named method in the parent class and child class, then use super keyword with the method name inside one method which belongs to child class,to access the methodpresent in the parent class

class student{
void show(){
System.out.println("this is student method");
}
}
class girl extends student{
void show1(){
super.show();
}
void show(){
System.out.println("this is girl method");
}
}
class main11{
public static void main(String[] args){
girl obj=new girl();
obj.show();
obj.show1();
}
}

Output

this is girl method
this is student method

super keyword can be used to invoke immediate parent class constructor

parent class can be invoked by using super( ) inside the child class constructor

class student{
student(){
System.out.println("Student Class");
}
}
class girl extends student{
girl(){
super();
System.out.println("Girl Class");
}
}
class main11{
public static void main(String[] args){
girl obj=new girl();
}
}

Output

Student Class
Girl Class
Last updated on by vishal devxo