简体   繁体   English

约束超类不能覆盖子类的值

[英]constraint a super class can not override the value of subclass

This method is in a Scores class, that is set the class variable scores, but the scores is combination of its sub class, for example, scores = sub scores1 + sub scores2 , sub1/sub2 is calculated by the subclasses of Scores. 此方法在Scores类中,该类设置了类别变量scores,但是分数是其子类的组合,例如, scores = sub scores1 + sub scores2 ,sub1 / sub2由Scores的子类计算。

public void setScores (double scores) {
    this.scores = scores;
}

public void calculateScore(double sub1, double sub2) {
    this.scores = (sub1 + sub2) /2;
}

is there method/design skills/practice to constraint the class can't alter the scores value (ie run the setScores), after the calculateScore() just ran. 是否有方法/设计技能/惯例来限制类不能更改分数值(即运行setScores),仅在calculateScore()运行之后。

摆脱这两种方法,并实现final double getScores(double sub1, double sub2)进行计算,并返回所需的结果。

You could use a flag calculated and if it is true, throw an exception in setScores(...) . 您可以使用calculated的标志,如果它为true,则在setScores(...)引发异常。 Note that this approach only will enforce that constraint at runtime and you might miss a situation that throws the exception in your test. 请注意,这种方法只会在运行时强制执行该约束,并且您可能会错过在测试中引发异常的情况。

Generally it would be favorable to enforce the constraint at compile time, but we'd need some more information. 通常,在编译时强制执行约束是有利的,但是我们需要更多信息。 Here's an idea based on guesses on your other constraints: 这是一个基于您其他约束条件的猜测的想法:

You could also pass the scores to the constructor if you want setScores(...) to be called only once. 如果只想一次调用setScores(...) ,也可以将分数传递给构造函数。 In this case you either completely get rid of setScores(...) or make in protected to allow only this class, subclasses and classes in the same package to call it. 在这种情况下,您要么完全摆脱了setScores(...)要么进行保护以仅允许此类,子类和同一包中的类来调用它。

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

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