简体   繁体   English

从子类操作父类的私有变量

[英]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 .我为两个类提供了 UML,父类base类的变量balance列为私有成员 (-),子类child I've created the public getters/setters for balance .我已经为balance创建了公共 getter/setter 。 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 .子类有一个 void 函数interest ,它应用适当的方程来计算利息(具有给定的利率)并将结果存储回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.当我尝试以下操作时,我收到错误: error: unexpected type ,我知道我不能做balance =...因为balance是私有的。

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.我想到的唯一方法是使用 protected 而不是 private 来balance ,但教授对坚持 UML 非常严格。

You said you created public getters and setters, judging from your code it seems the getter is called getbalance .你说你创建了公共 getter 和 setter,从你的代码来看,getter 似乎被称为getbalance You can use the setter, then, I'll assume it's called setbalance .您可以使用 setter,然后,我假设它称为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):此外,您不需要显式使用super ,因为属于父类的公共方法会自动传递给子类(尽管您可以,如果您愿意):

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

First thing to say, is that protected was invented just for the use case you are talking about.首先要说的是, protected是为您正在谈论的用例而发明的。 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.现在,如果我们正在理论化并且您的老师希望它是私密的,您就坚持使用 getter/setter。 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 .你甚至不需要使用super Use it only in constructors, or when you are overriding methods and want to refer to the implementation in the parent.仅在构造函数中使用它,或者当您覆盖方法并希望引用父级中的实现时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM