Java Super Keyword with Example

Java Super Keyword with Example

Java super is a keyword is used to access the method or member variables(instance variables) from the Super class.

What is The Use of Super keyword?

  1. super.instance_variable_name is used to refer the super class instance variables.
  2. super.method_name is used to refer the super class methods.
  3. super() is used to refer the super class constructor.
1.super.instance_variable_name is used to refer the Super class instance variables.
Example
class Parent {
int x = 1000;

}

public class Child extends Parent {

private int x = 2000;

public void showValue() {
System.out.println("parent instace variable value:" + super.x);
System.out.println("child instace variable value:" + x);
}

public static void main(String[] args) {
Child c = new Child();
c.showValue();

}

}
output

2.super.method_name is used to refer the super class methods
Example
 class Parent {
public void printMethod() {
System.out.println("parent method");
}

}
public class Child extends Parent {

public void printMethod() {
System.out.println("child method");
}

public void showValue() {
printMethod();
super.printMethod();
}

public static void main(String[] args) {
Child c = new Child();
c.showValue();

}

}
output


3.super() is used to refer the super class constructor.
Example
class Parent {

public Parent() {
System.out.println("parent class constructor");
}

}
public class Child extends Parent {

public Child() {
super();
System.out.println("child class constructor");
}

public static void main(String[] args) {
Child c = new Child();

}

}
output

-->