如何建议接口的植入具有某些指定的数据成员?

时间:2018-07-18 19:22:06

标签: java class oop inheritance

我希望实现myInterface的类应具有一些特定的数据成员。 但是,如果我在界面中指定它们,它们将成为最终的。那么,有什么办法可以通过在接口中声明一个方法来建议他们创建一个特定的数据成员?

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
    }
}

1 个答案:

答案 0 :(得分:3)

不可能要求接口的子代创建字段。为了暗示这一点,您总是可以向接口添加更多方法,这些方法要求子类返回idname,然后使用默认方法在接口内对其进行验证。

public interface MyInterface {
    default boolean idNameSafe() {
        // Perform your check(s) here using getId() and getName()
    }

    int getId();

    String getName();
}