SHADOWED VARIABLES

CONTENTS

1. Introduction
2. Example
2. Accessing shadowed variables using a cast


1. Introduction

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.



2. EXAMPLE

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).

// 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);
        }
    }

Table 1:Class hierrachy

// 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();
	}
    }

Table 2: Application class

$ java  ExampleApp
ClassOne avaerage = 4
ClassOne avaerage = 6          

Table 3: Sample output



3. ACCESSING SHADOWED VARIABLES USING A CAST

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:

System.out.println("ClassOne avaerage = " + ((ClassOne)this).average);

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