[英]How can access to a private variable in another class by using a getter function?
First class(The parent class)一级(父级)
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();
}
}
The other class(The child class)其他班级(子班级)
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();
}
}
How can access to a private variable in another class by using a getter function ?如何使用 getter 函数访问另一个类中的私有变量? And how can i change it in the child class ?
我如何在子类中更改它?
You can use method in child like this您可以像这样在孩子中使用方法
public void changeExThis() {
y = 20;
System.out.println("x = " + UnprivateX());
System.out.println("y = " + y);
}
Also you can use this.UnprivateX()
or super.UnprivateX()
你也可以使用
this.UnprivateX()
或super.UnprivateX()
First of all, you should declare all fields of class as private, then create getters and setters for each one and they have to have names start with getFieldName & setFieldName.首先,您应该将类的所有字段声明为私有,然后为每个字段创建 getter 和 setter,它们的名称必须以 getFieldName 和 setFieldName 开头。 and should be public.
并且应该是公开的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.