I want to access two private variables from the superclass MathProblem
, but I don't know how to access them. 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. So my question is: Is there any way I can access them?
Use the protected
access modifier instead of 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.