Why are protected instance members not visible inside a subclass in another package, but protected class members?

package one;

public class A {
    protected int first;
    protected static int second;
}

package two;

import one.A;

public class B extends A {
    public void someMethod() {
        this.first = 5; //works as expected
        B.second = 6; //works
        A a = new A();
        // a.first = 7; does not compile

        //works just fine, but why?
        a.second = 8; 
        A.second = 9;
    }
}

Why don't the same restrictions apply to static fields, what is their idea?

+6
source share
1 answer

From JLS 6.6.2 :

A protected member or constructor of an object can be accessed from outside the package in which it is declared only by the code responsible for the implementation of this object.

From 6.6.2.1 :

Let C be the class in which the protected member is declared. Access is permitted only inside the body of subclass S of C.

this.first = 5;It works because it Bis a developer A.

A.second , . B.second.

, , , , - . 6.6.2.1 , , :

, :

package points;
public class Point {
    protected int x, y;
    void warp(threePoint.Point3d a) {
        if (a.z > 0)  // compile-time error: cannot access a.z
            a.delta(this);
    }
}

threePoint :

package threePoint;
import points.Point;
public class Point3d extends Point {
    protected int z;
    public void delta(Point p) {
        p.x += this.x;  // compile-time error: cannot access p.x
        p.y += this.y;  // compile-time error: cannot access p.y
    }
    public void delta3d(Point3d q) {
        q.x += this.x;
        q.y += this.y;
        q.z += this.z;
    }
}

delta : x y p, , Point3d (, x y), Point (, x y), ( p). delta3d q, Point3d Point Point3d.


protected static Java.

protected - protected static protected, .

+6

All Articles