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

问题描述 投票:0回答:2

头等舱(父类)

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

java getter-setter
2个回答
0
投票

您可以在像这样的孩子中使用方法

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.