Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manipulating Private variables of parent class from child class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading