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

Dan Smith daniel.smith at oracle.com
Fri Oct 7 15:22:20 PDT 2011


On Oct 7, 2011, at 12:57 PM, David M. Lloyd wrote:

> On 10/07/2011 02:29 PM, Peter Levart wrote:
>> This code compiles with latest JDK 6 javac:
>> 
>> 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.outerField;
>>         }
>>     }
>> 
>>     public static void main(String[] args)
>>     {
>>         Outer outer = new Outer(12);
>>         Inner<Outer>  inner = new Inner<Outer>();
>>         System.out.println(inner.getOuterField(outer));
>>     }
>> }
>> 
>> 
>> ... but refuses to compile with JDK 7 javac (release or latest 7u2-b08 prerelease), giving the
>> following compilation failure:
>> 
>> src/test/Outer.java:16: error: outerField has private access in Outer
>>             return outer.outerField;
>>                         ^
>> 
>> even if tried with -source 1.6 -target 1.6 options.
>> 
>> Is this intentional or a bug?
> 
> I'd say it's a bug, according to JLS §6.6.1 access to a private member is "permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor."  Looks to me like the access on line 16 occurs within the body of the top-level class (Outer) that encloses the declaration.

Yes, the field is accessible, per 6.6.1.  But this is irrelevant, because it's not a member of the type O at all!  See 4.4, 4.9, and 6.5.6.2.

The same problem would come up if O were a class rather than a type variable:

public static class Inner {
  public static class O extends Outer {}
  public int getOuterField(O outer) { return outer.outerField; }
}

—Dan




More information about the compiler-dev mailing list