Monday, January 01, 2007

strange "overridden" java field

In Java, fields could also be "overridden", and for each overridden field, a copy of memory is allocated. These versions of field could be only accessed by means of type casting. This seems strange enough--what's the point to have "overridden" fields? Are there better ways to access those "versions" of fields?

For example, the output of the following program will be:
t.f=3 p.f=1


public class FieldSignatures {
static class P {
int f;
}

static class S extends P {
int f;
}

static class T extends S {
T() {
((P)this).f = 1;
((S)this).f = 2;
this.f = 3;
}
}

public static void main(String[] args) {
T t = new T();
P p = t;
System.out.println("t.f="+t.f+" p.f="+p.f);
}
}

1 comment:

Kenyth said...

Never notice this overridden field issue, because generally I will never override a field when using Java. Thanks for pointing out.