|
1. Introduction | |
2. Example | |
2. Accessing shadowed variables using a cast |
Overriding is occures where a method in a sub-class has the same name and arguments as that of a method in its super-class. A similar situation can exist with variables where a variable occurs in a sub-class with the same name as a variable in its super-class. In this case the variable in the sub-class is said to shaddow the variable in the super-class.
If we should wish to acces the super-class version of the variable we must
use the reserved word super.
Consider the hierartchy presented in Table 1. Here we have a class
ClassOne which contains a field average. We also have a class
ClassTwo which also conatins a varaibale average which
therefore "shaddows" the parent variable. Note, however, that we can still
access the parent variable uysing the super reserved word. (The
application class to go with this code is given in Table 2, and some3 sample
output in Table 3). Table 1: Table 2: Application class Table 3: Sample output An alternative to using the reserved word this, as used in the above
example, is to temporerilly cast the sub-class to
be an instance of its super-calls. Thus we could include the following line in
the output method given in Table 1: This technique is useful if we wish to refer to a shadowed variable in a
class beyond the immediate super-class. Created and maintained by
Frans Coenen.
Last updated 23 March 2000
2. EXAMPLE
// Shadow variable Example Class One
// Frans Coenen
// 24 March 2000
// Dept Computer Science, University of Liverpool
class ClassOne {
// ------------------- FIELDS ------------------------
protected int average = 6;
}
// Shadow variable Example Class Two
// Frans Coenen
// 24 March 2000
// Dept Computer Science, University of Liverpool
class ClassTwo extends ClassOne {
// ------------------- FIELDS ------------------------
private int average = 4;
// ------------------ METHODS ------------------------
public void output() {
System.out.println("ClassOne avaerage = " + average);
System.out.println("ClassOne avaerage = " + super.average);
}
}
// Example Program
// Frans Coenen
// 24 March 2000
// Dept Computer Science, University of Liverpool
class ExampleApp {
// ------------------ METHODS ------------------------
/* Main method */
public static void main(String[] args) {
// create instance of ClassTwo
ClassTwo newInst = new ClassTwo();
// Output
newInst.output();
}
}
$ java ExampleApp
ClassOne avaerage = 4
ClassOne avaerage = 6
3. ACCESSING SHADOWED VARIABLES USING A CAST
System.out.println("ClassOne avaerage = " + ((ClassOne)this).average);