[英]how to access a private values from the super class in Java?
I want to access two private variables from the superclass MathProblem
, but I don't know how to access them. 我想从超类MathProblem
访问两个私有变量,但是我不知道如何访问它们。 I know that the private things are not inherited, but I need those two variable to access them and add them and return the value. 我知道私有事物不会被继承,但是我需要那两个变量来访问它们并添加它们并返回值。
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;
}
}
And the sub class is like this: 子类是这样的:
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;
}
}
So in class AdditionMathProblem
, I used the getOperand1() + getOperand2()
to add the two values, but I need those two values letter to access them. 因此,在类AdditionMathProblem
,我使用了getOperand1() + getOperand2()
来添加两个值,但是我需要使用这两个值来访问它们。 So my question is: Is there any way I can access them? 所以我的问题是: 有什么办法可以访问它们?
Use the protected
access modifier instead of private
. 使用protected
访问修饰符,而不是private
。 This will allow subclasses to access the members of their base class. 这将允许子类访问其基类的成员。
You cant access private variables directly from outside its class. 您不能直接从其类外部访问私有变量。 If you would like that variable to be accessible by its parent then you can: 如果希望该变量可由其父级访问,则可以:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.