gpt4 book ai didi

java - 仅出于履行契约(Contract)的目的而在方法签名中包含 args 是否是常见的做法

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:54 25 4
gpt4 key购买 nike

我有点好奇我在学校看到的一些代码,以及这是否是该领域的普遍做法或仅仅是糟糕的设计。

考虑以下接口(interface)和实现它的两个类...

public abstract interface Anchor
{
public abstract double x(double x);

public abstract double y(double y);
}

注意在 Cycle 类中实际使用了 x() 和 y() 中的参数...

public class Cycle implements Anchor
{
public Anchor anchor;
public double radius;
public double period;
public double phase = 4.0D;

public Cycle(Anchor anchor, double radius, double period) {
this.anchor = anchor;
this.radius = radius;
this.period = period;
}

public double angle(double day) {
return this.phase * 3.141592653589793D * (day / this.period) / 2.0D;
}

public double x(double x) {
return this.anchor.x(x) + Math.cos(angle(x)) * this.radius;
}

public double y(double y) {
return this.anchor.y(y) + Math.sin(angle(x)) * this.radius;
}
}

但在 Center 类中,x() 和 y() 中的参数仅用于实现与 Anchor 接口(interface)的联系,实际上并未在方法中使用...

public class Center implements Anchor
{
public double x;
public double y;

public Center(double x, double y) {
this.x = x;
this.y = y;
}

public double x(double x) { return this.x; }
public double y(double y) { return this.y; }
}

这是您在生产 Java 代码中常见的东西吗?这是公认的做法还是糟糕的变通办法?

最佳答案

是的,这对所有 OOP 代码都很常见。

接口(interface)定义了一组方法,这些方法可用于实现该接口(interface)的任何对象。这些方法的实现是调用者不应该关心的事情,并且在接口(interface)中看到的某些参数不适用于某些实现一点也不奇怪。

关于java - 仅出于履行契约(Contract)的目的而在方法签名中包含 args 是否是常见的做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7458450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com