Question

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

Was it helpful?

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.

OTHER TIPS

In reply to @Joachim - too long for a comment.

It is consistent with the fact that this would not compile:

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

(where SubTest extends Test) whereas this would compile

void method(SubTest hey) {
    String s = ((Test) hey)._canYouSeeMe;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top