那个部分
Any access to an a variable must be done through protected methods in the sub classes.
…只是意味着子类必须调用超类中定义的受保护方法.由于这些方法受到保护,因此子类可以访问它们.
首先,您将定义一个这样的基类:
public class Base {
private int x; // field is private
protected int getX() { // define getter
return x;
}
protected void setX(int x) { // define setter
this.x = x;
}
}
然后你会在你的子类中使用它,如下所示:
class Child extends Base{
void foo() {
int x = getX(); // we can access the method since it is protected.
setX(42); // this works too.
}
}