Super keyword in Java

The super keyword in Java can be used as following.

  • To invoke immediate parent class method.
  • To invoke immediate parent class constructor
  • To refer immediate parent class data members

Example of super keyword to invoke parent class constructor

Syntax to invoke parent class contructor

super(argument1,argument2,…argument N);


class Person{

private String name;

public Person(String name){

this.name=name;

}

}

class Student extends Person{

private String course;

public Student(String name,String course){

super(name); //this invoke Parent(String name)

}

}

Example of super keyword to invoke parent class method

Syntax to invoke parent class method.

super.methodName(argument1,argument2,…argument N);


class Person{

 private String name;

 public Person(String name){

 this.name=name;

}
public void display(){

 System.out.println("Name:"+name)
}

}

class Student extends Person{

 private String course;

 public Student(String name,String course){

 super(name); //this invoke Parent(String name)

}
public void display(){
 super.display();
 System.out.println("Course:"+course);
}

}

Example of super keyword to access parent class data member

Syntax to access parent class protected or public data members only.

super.dataMemberName


class Person{

protected String name;

public Person(String name){

this.name=name;

}

}

class Student extends Person{

private String course;

public Student(String name,String course){

super(name); //this invoke Parent(String name)

}
public void display(){
System.out.println("Name:"+super.name);
System.out.println("Course:"+course);
}

}

Leave a Reply