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:
- super may only be used within a subclass constructor or method.
- The class of superclass constructor must appear as the first statement within the subclass constructor.
- 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:
- The first calls the superclass's constructor.
- 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 i. ClassB 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