Abdirahim Deheye
Abdirahim Deheye

Reputation: 3

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. 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?

Upvotes: 0

Views: 123

Answers (2)

Sello Mkantjwa
Sello Mkantjwa

Reputation: 1915

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:

  1. Change modifier from private to protected. Or
  2. If you want the variable to remain private then you can create a publec method that returns that variable. Then from the child class just call that method.

Upvotes: 0

Justin Skiles
Justin Skiles

Reputation: 9523

Use the protected access modifier instead of private. This will allow subclasses to access the members of their base class.

Upvotes: 2

Related Questions