Search code examples
javagenericsjava-7private-membersgeneric-method

Why is a parameter's private field visible to a generic method in Java 6 but not in Java 7?


Possible Duplicate:
Type-parameterized field of a generic class becomes invisible after upgrading to Java 7

public class Test{

    private String _canYouSeeMe = "yes";

    <T extends Test> void genericMethod(T hey){
        String s = hey._canYouSeeMe;
    }

    void method(Test hey){
        String s = hey._canYouSeeMe;
    }   
}

When building against JDK 1.6 this compiles just fine but against 1.7 there is a compiler error in genericMethod(): The field Test._canYouSeeMe is not visible

The error can be resolved by making _canYouSeeMe protected rather than private, but I'm just wondering what has changed from 1.6 to 1.7


Solution

  • Subclasses (T) of a class (Test) never have access to the superclass' private fields. This was likely a bug in the Java 6 compiler that was fixed in Java 7.

    Remember: T extends Test means that T is a subclass of Test. It does not mean that T's class is Test.class, which is the necessary condition for having private field & method access.