gpt4 book ai didi

java - 覆盖变量还是强制使用?

转载 作者:行者123 更新时间:2023-12-01 06:30:16 24 4
gpt4 key购买 nike

我想强制一个类从它实现的类中定义某个变量。例如

class Fruit{
String name; // Cause each fruit has a name
}

//Apple wants to get an error if it does not use the name variable
class Apple implements Fruit {
String name = "Apple";
}

有办法做到这一点吗?就像 java.io.Serialized 一样吗?

最佳答案

我认为最简单的方法是使用构造函数。

class Fruit{
private final String name;
public Fruit(String name){
if (/* name has an incorrect value, is null or whatever */)
throw new IllegalArgumentException("name");
this.name = name;
}
}

//Apple wants to get an error if it does not use the name variable
class Apple extends Fruit {
public Apple(){ super("Apple"); }
}

现在不可能创建一个不将名称传递给 Fruit 构造函数的 Fruit 子类。通过将字段设置为final,您还可以获得额外的好处,一旦该字段被设置为正确的值,子类就不能在那里放置虚假的东西(除了使用反射等,但所有的赌注)已关闭)。

编辑:此外,正如更细心的发帖者所指出的,您不是实现类,而是扩展它们。对于接口(interface)(您执行实现),您无法强制从方法返回合理的值(不是以任何简单的方式 - 我想您可以使用 AOP 来检查返回值并在返回虚假值时抛出 IllegalStateException)。

关于java - 覆盖变量还是强制使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1531610/

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