Home > Net >  Manipulating Private variables of parent class from child class
Manipulating Private variables of parent class from child class

Time:11-16

I am provided with UML's for two classes, the parent class base which has variable balance listed as a private member (-), and a child class, child. I've created the public getters/setters for balance. Child class has a void function interest that applies the appropriate equation to calculate interest (with given interest rate) and stores the result back in balance.

public class base{
    private double balance;
    //constructors and getter/setters
}

When I try the following I get the error: error: unexpected type and I'm aware that I can't do balance =... since balance is private.

public class child extends base{
    private double interestRate;
    //constructors and getter/setters
    public void interest(){
        super.getbalance()*=Math.pow((1 interestRate/12), 12);
    }
}

The only way I've thought of doing this is through using protected instead of private for balance, but professor is pretty strict about sticking to the UML's.

CodePudding user response:

You said you created public getters and setters, judging from your code it seems the getter is called getbalance. You can use the setter, then, I'll assume it's called setbalance. Also, you do not need to explicitly use super, since public methods belonging to the parent class are automatically passed to the child class (although you can, if you prefer):

    public void interest(){
        setbalance(getbalance()*Math.pow((1 interestRate/12), 12));
    }

CodePudding user response:

First thing to say, is that protected was invented just for the use case you are talking about. So, apart from the reason to make your teacher happy (or being an unreasonable purist) , I don't see a reason why not to use it here. In real life cases you should use it just like that.

Now, if we are theorizing and your teacher wants it private, you stick to the getters/setters. Nothing can stop you to use them, even from the child class.

public void interest(){
    setBalance(getBalance()*=Math.pow((1 interestRate/12), 12));
}

You don't even need to use super. Use it only in constructors, or when you are overriding methods and want to refer to the implementation in the parent.

  •  Tags:  
  • java
  • Related