Monday, July 6, 2009

Shadowing final variables

In Java, final variables can be shadowed. They follow the same rules of shadow variables and static methods which I had discussed in my earlier post. The key point to remember is that while resolving a shadow variable or shadow static method, the reference type and NOT the reference object (i.e. object pointed to by the reference type) is used. Here is a simple example:

class Super {
public final String y = "SUPER";
public static final int z = 0;

class Sub extends Super {

//Shadowing a final variable
public final String y = "SUB";

//Shadowing a final variable and also changing type and access modifier's
char z = '1';


public class ShadowingFinalVariables {

public static void main(String[] args) {
Sub sub = new Sub();
Super supr = sub;

print(sub.y); //yields SUB
print(supr.y); //yields SUPER
print(((Super)sub).y); //Due to casting, yields SUPER
print(((Sub)supr).y); //Due to casting, yields SUB
print(sub.z); //yields 1
print(supr.z); //yields 0
print(((Super)sub).z); //Due to casting, yields 0
print(((Sub)supr).z);//Due to casting yields 1


public static <T> void print(T t) {


1 comment:

  1. Thanks for sharing this.
    This approach can be useful for my project related to data room m&a services maintenance.