我如何在调用 super 时简化这个数学运算?

How can I simplify this mathematic operation in my call to super?

我正在尝试做一个项目,模拟一家销售各种甜点的杂货店。目前,我正在尝试为分层蛋糕创建一个 class,它源自蛋糕 class,蛋糕本身源自抽象甜点 class。本质上,蛋糕 class 的构造函数有两个参数,名称和价格。对于千层蛋糕,价格为底价+顶价+总价的10%。我已经找到了一种方法来执行此操作,但这是一行非常长且丑陋的代码。我尝试了几种方法来尝试使用变量来简化它,但我似乎无法找到一种方法来处理它是在 super() 中完成的事实。有没有办法让它更简单、更高效?提前致谢!

代码如下:

public class TieredCake extends Cake {
    private Cake base;
    private Cake top;

    public TieredCake (Cake base, Cake top) {
        super(base.getName() + " with an upper tier of " + top.getName(), (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice()+top.getPrice());
        this.base = base;
        this.top = top;
    }

    public Cake getBase() {
        return base;
    }

    public Cake getTop() {
        return top;
    }
}

将对 super 的调用拆分到多行中会有所帮助:

public TieredCake(Cake base, Cake top) {
    super(
        base.getName() + " with an upper tier of " + top.getName(),
        (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice() + top.getPrice()
    );

    this.base = base;
    this.top = top;
}

但更重要的是,让我们来看看那个公式。我们可以在数学层面上做一些简化:

B := base.getPrice()
T := top.getPrice()

(B + T) * 0.1 + B + T
= (B * 0.1) + (T * 0.1) + B + T
= (B * 1.1) + (T * 1.1)
= (B + T) * 1.1

这给了我们:

public TieredCake(Cake base, Cake top) {
    super(
        base.getName() + " with an upper tier of " + top.getName(),
        (base.getPrice() + top.getPrice()) * 1.1
    );

    this.base = base;
    this.top = top;
}