Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中如何从超类访问私有值?_Java - Fatal编程技术网

在Java中如何从超类访问私有值?

在Java中如何从超类访问私有值?,java,Java,我想从超类MathProblem中访问两个私有变量,但我不知道如何访问它们。我知道私有的东西不是继承的,但是我需要这两个变量来访问它们,添加它们并返回值 abstract public class MathProblem { private int operand1; private int operand2; private int userAnswer; public MathProblem() { operand1 = RandomUtil

我想从超类
MathProblem
中访问两个私有变量,但我不知道如何访问它们。我知道私有的东西不是继承的,但是我需要这两个变量来访问它们,添加它们并返回值

abstract public class MathProblem {
    private int operand1;
    private int operand2;
    private int userAnswer;

    public MathProblem() {
        operand1 = RandomUtil.nextInt(99);
        operand2 = RandomUtil.nextInt(99);
    }

    public int getOperand1() {
        return operand1;
    }

    public void setOperand1(int operand1) {
        this.operand1 = operand1;
    }

    public int getOperand2() {
        return operand2;
    }

    public void setOperand2(int operand2) {
        this.operand2 = operand2;
    }

    public int getUserAnswer() {
        return userAnswer;
    }

    public void setUserAnswer(int userAnswer) {
        this.userAnswer = userAnswer;
    }
}
子类是这样的:

public class AdditionMathProblem extends MathProblem {
    StringBuilder sb = new StringBuilder();

    public AdditionMathProblem() {
        super();
        // can't access the private values.
    }

    @Override
    public int getAnswer() {    
        int result = getOperand1() + getOperand2();
        return result;
    }
}   

因此,在类
AdditionMathProblem
中,我使用
getOperator1()+getOperator2()
来添加这两个值,但我需要这两个值的字母来访问它们。所以我的问题是:有什么方法可以访问它们吗?

使用
受保护的
访问修饰符,而不是
私有的
。这将允许子类访问其基类的成员。

您不能直接从其类外访问私有变量。如果您希望该变量可由其父变量访问,则可以:

  • 将修改器从私有更改为受保护。 或
  • 如果希望变量保持私有,则可以创建一个返回该变量的publec方法。然后从子类调用该方法
    您已经为操作数定义了
    public
    get/set
    方法;为什么你不能用它们来访问值?我需要值字母。如果两个操作数都有getter和setter,为什么你需要直接访问字段?getter和setter实际上提供了你需要的所有东西,所以你没有真正向我们解释问题出在哪里。显然,最好的办法是,但是因为OP没有说原来的类是可修改的,所以我想出了一个解决办法。