Perhaps you need to create a subclass to add new capabilities and
so will override a method in the base class. However, you want to
take advantage of code already in the overridden method rather than
re-writing it in the overriding method.
You can obtain access to overriden methods and data with the super
reference. In the following code, class B
overrides a method in class A
but calls the overridden method using the super
reference:
|
public
class A {
int i = 0;
void doSomething (){ i = 5;}
}
class B extends A {
int j = 0;
void doSomething () {
j = 10;
// Call the
overridden method
super.doSomething
();
// And can
use the shadowed
// property
j = j + i;
}
}
|
You cannot cascade super
references to access variables more than one class deep as in
j
= super.super.i; // error, not a valid
use of super
This would seem logical but it is not allowed. Only the immediate
superclass's data and methods can be accessed.
Note: Though one can override
data variables (the overridden data is referred to as shadowed
data), it is seldom useful and potentially very confusing.
We can also explicitly reference instance variables in the current
object with the this
reference. The code below illustrates a common technique to distinguish
argument variables from instance or class variables:
public
class A {
int x,y;
void doSomething (int x, int y) {
// x & y hold
the values passed in
// the argument variables. To access
// the instance variables x,y we
must
// specify them with 'this'.
this.x
= x;
this.y
= y;
}
}
|
Here the argument variables shadow the instance variables with
the same variable names. However, the this
reference explicitly indicates that the particular data names belong
to the particular instance of the class.
Note: Do not confuse the
this and
super
references with the this()
and super()
constructor invocations, which we discuss next.
Latest Update: Oct. 24, 2004
|