Java Super Keyword with Example

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

 Use of Super keyword
  1. super.instance_variable_name is used to refer to the parent class data members(instance variables).
  2. super.method_name is used to access the parent class methods.
  3. super() is used to refer to the parent class constructor.
1.super.instance_variable_name is used to refer to the parent class instance variables.
Let's have a look at the below example, in Parent class and Child class we have the same instance variable called "x" and we have called super.x in the Child class method(showValue() method). from the output, we can conclude that we can access the Parent class instance variables by usingsuper.instance_variable_name.
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 to the Parent class methods
when we override the parent class method in the child class we can access the parent class method in child class by using super.method_name. Let's have a look at the below example

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 to the parent class constructor.
super() will call the parent class constructor i.e. whenever we create the child class Object JVM will invoke the constructor of the child class which will internally call the parent class constructor. Let's have a look at the below example
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

No comments:

Post a Comment

-->