![](/img/trans.png)
[英]Object oriented programming, getter is not getting private variable from another class
[英]How can access to a private variable in another class by using a getter function?
一級(父級)
package revisionOOP;
public class Myclass {
private int x;
public void changeThis() {
x = 10;
System.out.println("x = " + x);
}
//getter
public int UnprivateX() {
return this.x;
}
public static void main(String[] args) {
Myclass inst = new Myclass();
inst.changeThis();
}
}
其他班級(子班級)
package revisionOOP;
public class MySecondClass extends Myclass {
static int y;
public void changeExThis() {
y = 20;
System.out.println("x = " + inst.UnprivateX());
//I want to get the private x value from Myclass class ,How ?
System.out.println("y = " + y);
}
public static void main(String[] args) {
MySecondClass inst = new MySecondClass();
Myclass inst2 = new Myclass();
inst2.changeThis();
inst.changeThis();
inst.changeExThis();
}
}
如何使用 getter 函數訪問另一個類中的私有變量? 我如何在子類中更改它?
您可以像這樣在孩子中使用方法
public void changeExThis() {
y = 20;
System.out.println("x = " + UnprivateX());
System.out.println("y = " + y);
}
你也可以使用this.UnprivateX()
或super.UnprivateX()
首先,您應該將類的所有字段聲明為私有,然后為每個字段創建 getter 和 setter,它們的名稱必須以 getFieldName 和 setFieldName 開頭。 並且應該是公開的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.