Thy*_*hys 0 java variables interface
我想强制一个类从它实现的类中定义一个特定的变量.例如
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";
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?就像java.io.Serializable一样吗?
gus*_*afc 11
我想,最简单的方法是使用构造函数.
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"); }
}
Run Code Online (Sandbox Code Playgroud)
现在不可能创建一个Fruit没有将名称传递给Fruit构造函数的子类.通过制作该字段final,您还可以获得额外的奖励,一旦将字段设置为适当的值,子类就不能在那里放置虚假的东西(除了使用反射等,但是所有的赌注都关闭).
编辑:另外,正如更贴心的海报所指出的,你不是implement课,你是extend他们.对于接口(你这样做 implement),你不能强制从方法中返回合理的值(不是以任何简单的方式 - 我想你可以使用AOP来检查返回值并抛出IllegalStateException返回的伪值).
| 归档时间: |
|
| 查看次数: |
4002 次 |
| 最近记录: |