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();
   }
}
raja
Published on 15-Feb-2019 11:33:39
Advertisements