Acces to private field from nested class when the type of reference is a generic type variable with upper bound of outer class
Peter Levart
peter.levart at gmail.com
Fri Oct 7 14:54:00 PDT 2011
On Friday, October 07, 2011 11:15:13 PM maurizio cimadamore wrote:
> An intersection type A1, A2 ... An is defined as the most general type
> that is a subtype of both A1, A2 ... An.
> Since it is a subtype of all its components, it follows it should
> contain the members of the 'union' of the components. However, since
> it's a subtype, private members in supertypes are not inherithed.
>
> Maurizio
Quite true. And that's understandable for private field access.
And now for some puzzlers. Let's take that definition and a look at the following program:
package test;
public class Test
{
public static class A
{
public int field = 1;
}
public static class B extends A
{
public int field = 2;
}
public static class FieldGetter<T extends A>
{
public int getField(T obj)
{
return obj.field;
}
}
public static void main(String[] args)
{
A a = new A();
B b = new B();
FieldGetter<A> aFieldGetter = new FieldGetter<A>();
FieldGetter<B> bFieldGetter = new FieldGetter<B>();
System.out.println(a.field); // 1
System.out.println(b.field); // 2
System.out.println(aFieldGetter.getField(a)); // 1
System.out.println(aFieldGetter.getField(b)); // 1
System.out.println(bFieldGetter.getField(b)); // 1 !!!
}
}
... in FieldGetter the T is the most general type that is a subtype of A and any subtypes of A
(which includes B). Now A.field is inherited by any subtypes of A, but it can also be hidden by
fields of the same name in any of the subtypes of A (as is in the example by B.field).
The question is: How can compiler decide which field to access in T.getField method?
Would it be right to disallow "any" field access via the type-variable typed variables?
The joys of erasure!
Peter
More information about the compiler-dev
mailing list