Sunday, 15 May 2011

Referring to base class members using super in java

Referring to base class from derived class, can be done with the help of super. Here super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form:

super.member


Here, member can be either a method or an instance variable.
class A {

int i;
}

// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}

void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}

}

No comments:

Post a Comment