Access to own private fields of a subclass object

This construct just does not compile:

class A {
    private int data;
    public static int process(B b) {
        return b.data;// error here: 'data has private access in A'
    }
}
class B extends A {}

Of course, this problem can be solved easily by hand (cast b in A, field protection, etc.). But the question is, why does Java not allow such a design? I thought that the compiler should know that B is a subclass of A, so methods A should have access to private fields.

The only possible problem that I can think of is that if B has its own data field, the compiler does not need to know in which field we want to access, but for what we inherit, right?

+4
source share
1 answer

, , . JLS 8.3 ( ) ( ):

, .

- , . , .

(6.5.6.2) - , , , , , : " B , data", , .

, , . # , . , # 5, 3.4:

, , , , . , - , , . - (§3.5.1), , (§3.7.1.2).

+1

All Articles