Acces to private field from nested class when the type of reference is a generic type variable with upper bound of outer class

David M. Lloyd david.lloyd at redhat.com
Fri Oct 7 14:03:39 PDT 2011


On 10/07/2011 03:45 PM, Peter Levart wrote:
> On Friday, October 07, 2011 10:13:10 PM David M. Lloyd wrote:
>> But the field _would_ be accessible according to JLS §6.6.1 regardless
>> of whether the object was of a subtype.  It seems pretty clear to me,
>> but maybe I'm just being dense?
>
> It's not the type of object that matters, but the type of variable.
>
> For example:
>
> public class A {
>    private int x = 1;
>
>    void m() {
>      B b = new B();
>      System.out.println(b.x); // no go
>      A a = b;
>      System.out.println(a.x); // prints 1
>    }
> }
>
> public class B extends A {
>    private int x = 2;
> }
>
>
> ... you see, the same object, but different types of variables A vs. B!
>
> The same goes for types that are expressed as type-variables. They are a conjunction of all
> possible types that match the bounds (if any). The language is sound if it does not "prefer"
> just one of them.

I see, so you'd have to add in the cast like this:

package test;

public class Outer
{
     private int outerField;

     public Outer(int outerField)
     {
         this.outerField = outerField;
     }

     public static class Inner<O extends Outer>
     {
         public int getOuterField(O outer)
         {
             return ((Outer)outer).outerField; // <- RIGHT HERE
         }
     }

     public static void main(String[] args)
     {
         Outer outer = new Outer(12);
         Inner<Outer> inner = new Inner<Outer>();
         System.out.println(inner.getOuterField(outer));
     }
}

I suppose that makes sense, though it rankles a bit since a widening 
cast is a pretty unusual thing to have to do in Java.

-- 
- DML



More information about the compiler-dev mailing list