gpt4 book ai didi

java - 当接口(interface) A 在其方法签名中定义接口(interface) B 时

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:54:05 25 4
gpt4 key购买 nike

...如何限制 A 的实现在方法签名中使用 B 的特定实现?

用例

这是一个 Unit 接口(interface)和两个实现它的枚举:

public interface Unit { ... }

public enum ForceUnit implements Unit { ... }
public enum MassUnit implements Unit { ... }

Property 接口(interface)使用:

public interface Property {

public void setUnit( Unit unit ); // for example
}

public class Force implements Property { ... }
public class Mass implements Property { ... }

在这里我希望能够强制执行:

  • ForcesetUnit 签名中仅使用 ForceUnit
  • MasssetUnit 签名中仅使用 MassUnit

当我尝试这样做时,Eclipse 提示:

The type Mass must implement the inherited abstract method Property.setUnit(unit)

并及时提出两个快速修复建议:

  • 将类抽象化,这不是一个选项,因为我希望能够执行类似 Mass mass = new Mass();
  • 的操作
  • 使用@Override 注释添加未实现的方法。我不知道这是否是正确的解决方法,但对我来说这有点笨拙。

问题

  • 我有哪些选择来实现我想要的?在这方面使用泛型会有帮助吗?
  • 为什么将类标记为抽象类可以解决问题?

最佳答案

你可以使用泛型

public interface Property<U extends Unit> {

public void setUnit(U unit ); // for example
}

public class Force implements Property<ForceUnit> {
@Override
public void setUnit(ForceUnit unit) { }
}

public class Mass implements Property<MassUnit> {
@Override
public void setUnit(MassUnit unit) { }
}

注意:这确实意味着您仍然可以这样做

Property raw = new Mass();
raw.setUnit(ForceUnit.NEWTON); // ClassCastException

然而,这将导致类转换异常,因为编译器无法在运行时检查原始类型。

你应该做的是

Property<Mass> raw = new Mass();
raw.setUnit(ForceUnit.NEWTON); // doesn't compile.

Why does marking the class as abstract resolve the issue?

将类抽象化意味着 setUnit(Unit) 实际上还没有实现,但对于抽象类来说这没问题。

关于java - 当接口(interface) A 在其方法签名中定义接口(interface) B 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35490690/

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