![](/img/trans.png)
[英]How to access a private field of the super class of the super class with reflection in Java?
[英]how to access a private values from the super class in Java?
我想从超类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
,我使用了getOperand1() + getOperand2()
来添加两个值,但是我需要使用这两个值来访问它们。 所以我的问题是: 有什么办法可以访问它们?
使用protected
访问修饰符,而不是private
。 这将允许子类访问其基类的成员。
您不能直接从其类外部访问私有变量。 如果希望该变量可由其父级访问,则可以:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.