我希望实现 myInterface 的类应该有一些特定的数据成员。 但如果我在界面中指定它们,它们就会成为最终的。那么有什么方法可以通过在接口(interface)中声明一个方法来建议他们创建一个特定的数据成员吗?
public interface myInterface{
boolean idNameSafe();
//add something that they make id and name datamember in their class
}
public class myClass implements myInterface{
//should have long id
//should have string name
//myClass's datamember
@Override
public boolean idNameSafe(){
//checks the id and name and does something on it
}
}
最佳答案
要求接口(interface)的子级创建字段是不可能的。为了暗示这一点,您总是可以向接口(interface)添加更多方法,要求子类返回 id
和 name
,然后使用默认方法在接口(interface)内验证它们.
public interface MyInterface {
default boolean idNameSafe() {
// Perform your check(s) here using getId() and getName()
}
int getId();
String getName();
}
关于java - 如何提示接口(interface)的植入有一些指定的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51409573/