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

StackOverflow https://stackoverflow.com/questions/11761358

سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top