简体   繁体   English

如何在Java接口中定义Getter和Setter(Property)

[英]How to define Getter and Setter (Property) in java interface

I want to use RMI in my application. 我想在我的应用程序中使用RMI。 So using the interface is compulsory. 因此,必须使用该界面。 I want to force the developer to implement getter and setters. 我想强迫开发人员实现getter和setter。 So I want to define the getter and setter methods in my interface. 所以我想在界面中定义getter和setter方法。 How can I do this? 我怎样才能做到这一点? Unfortunately there is no useful article or link to help me. 不幸的是,没有有用的文章或链接可以帮助我。 Any helps would be appreciated. 任何帮助将不胜感激。

public interface MyInterface {
    PropertyType getProperty();
    void setProperty(PropertyType property);
}

you can declare method in interface, you can not define it's body inside it. 您可以在接口中declare方法,而不能在其中define其主体。

Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. 接口在类和外部世界之间形成契约,并且该契约在编译时由编译器强制执行。 If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 如果您的类声称要实现一个接口,则在成功编译该类之前,该接口定义的所有方法必须出现在其源代码中。

It will be defined where that interface will be implemented. 将定义该interface实现位置。

Java doesn't have inbuilt support for get-set properties.You have define your own get-set properties like Java没有对get-set属性的内置支持。您已经定义了自己的get-set属性,例如

int getCount();
void setValue();

write your methods without body 不用身体写你的方法

public interface MyInteface {
    public String getSomething();
    public void setSomething(String str);
}

then any class that implements this interface has to implements these get/set methods 那么任何实现此接口的类都必须实现这些get / set方法

If you declare the getter and setter in the interface any reasonable IDE will tell you that you have to implement them in a class that implements the interface. 如果在接口中声明getter和setter,则任何合理的IDE都会告诉您必须在实现该接口的类中实现它们。 Even if the IDE does not tell you that, java will print out an error that is reasonable enough and easy to understand. 即使IDE不会告诉您,java也会打印出足够合理且易于理解的错误。 Little room for error there. 那里的错误空间很小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM