Role of super Keyword in Java Inheritance


Parent class objects can be referred to using the super keyword in Java. It is usually used in the context of inheritance. A program that demonstrates the super keyword in Java is given as follows:

Example

 Live Demo

class A {
   int a;
   A(int x) {
      a = x;
   }
}
class B extends A {
   int b;
   B(int x, int y) {
      super(x);
      b = y;
   }
   void print() {
      System.out.println("Value of a: " + a);
      System.out.println("Value of b: " + b);
   }
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B(7, 3);
      obj.print();
   }
}

Output

Value of a: 7
Value of b: 3

Now let us understand the above program.

The class A contains a data member a and constructor A(). The class B uses the extends keyword to derive from class A. It also contains a data member b and constructor B(). The method print() prints the values of a and b. A code snippet which demonstrates this is as follows:

class A {
   int a;
   A(int x) {
      a = x;
   }
}
class B extends A {
   int b;
   B(int x, int y) {
      super(x);
      b = y;
   }
   void print() {
      System.out.println("Value of a: " + a);
      System.out.println("Value of b: " + b);
   }
}

In the main() method in class Demo, an object obj of class B is created. Then the method print() is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      B obj = new B(7, 3);
      obj.print();
   }
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements