如何使用 getter 函数访问另一个 class 中的私有变量?

How can access to a private variable in another class by using a getter function?

第一class(第parentclass)

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();
    }
}

其他class(childclass)

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 函数访问另一个 class 中的私有变量? 我如何在 child class 中更改它?

您可以像这样使用 child 中的方法

public void changeExThis() {
    y = 20;
    System.out.println("x = " + UnprivateX());
    System.out.println("y = " + y);
}

你也可以使用 this.UnprivateX()super.UnprivateX()

首先,您应该将 class 的所有字段声明为私有,然后为每个字段创建 getter 和 setter,并且它们的名称必须以 getFieldName 和 setFieldName 开头。应该是 public.