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

Java 如何建议接口的植入有一些指定的数据成员?,java,class,oop,inheritance,Java,Class,Oop,Inheritance,我希望实现myInterface的类应该有一些特定的数据成员。 但若我在接口中指定它们,它们将成为最终的。所以,我建议他们在接口中声明一个方法来创建一个特定的datamember,有什么办法吗 public interface myInterface{ boolean idNameSafe(); //add something that they make id and name datamember in their class } public class myClass

我希望实现myInterface的类应该有一些特定的数据成员。 但若我在接口中指定它们,它们将成为最终的。所以,我建议他们在接口中声明一个方法来创建一个特定的datamember,有什么办法吗

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

不可能要求接口的子项来创建字段。为了提示这一点,您可以向接口添加更多方法,要求子类返回
id
name
,然后使用默认方法在接口内验证它们

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

    int getId();

    String getName();
} 

接口不关心实现,所以不。与强制实现者使用该变量相比,将接口定义为具有检索建议值的成员函数是否更有意义,这样,实现者需要以某种方式实现getter。@zero298但如果我在接口中编写它们,则该成员将成为最终成员。我不想这样final@LakshyaSharma当我说“成员”时,我指的是成员函数。