Program to use 'super' keyword to overcome name hiding

The super keyword is used to access base class constructor, variable and methods. A subclass can also explicitly call a constructor of its immediate super class. This is done by using the super keyword. The super keyword is used in following conditions:
  1. super may only be used within a subclass constructor or method.
  2. The class of superclass constructor must appear as the first statement within the subclass constructor.
  3. The parameters in the super call must match the order and type of the instance variable declared in the superclass.
super (parameter-list);

Super has two general forms:
  1. The first calls the superclass's constructor.
  2. The second is used to access a member (variable or method) of the superclass that has been declared as private.
In this program, we have declare ClassA which has a single variable iClassB extends ClassA which also have variable i. In its constructor we have called the superclass's variable.

PROGRAM
//Using super to overcome name hiding.
class ClassA {
 int i;
}

//Create a subclass by extending class ClassA.
class ClassB extends ClassA {
 
 int i; // this i hides the i in ClassA
 
 ClassB(int a, int b) {
 
  super.i = a; // i in ClassA
  i = b; // i in ClassB
 }
 
 void show() {
  
  System.out.println("i in superclass: " + super.i);
  System.out.println("i in subclass: " + i);
 }
}

public class UsingSuper {
 
 public static void main(String args[]) {
 
  ClassB subOb = new ClassB(1, 2);
  subOb.show();
 }
}
OUTPUT
C:\>javac UsingSuper.java
C:\>java UsingSuper
i in superclass: 1
i in subclass: 2

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative