我知道私有变量不是继承的,所以如何在我的子类中获得对它的访问?
即
class A{
private int i = 5;
// more code
}
class B extends A{
public int toInt(){
return super.i;
}
}
Run Code Online (Sandbox Code Playgroud)
通常,您将标记i为protected允许子类查看字段的标记.
另一种方法是编写一个get-style函数,有时可能更好,特别是如果你想禁止子类写入字段.编写a- putstyle函数确实会破坏封装.
反思也提供了另一种规避方法private,但不推荐使用这种方法.