我正在从导入的库中扩展一个非常简单的 Java 接口(interface)。该接口(interface)非常简单,它声明的唯一方法是属性列表的 getter 和 setter。
我的应用程序是用 Groovy 编写的,所以我想用 Groovy 类实现这个 Java 接口(interface)。
我的印象是 Groovy 默认为其类的任何属性创建 getter 和 setter - 我可以使用这些默认的 getter 和 setter 来满足 Java 接口(interface)的要求吗?
库的 Java 接口(interface):
public interface Animal { // java interface
public String getName();
public void setName(String name);
public Integer getAge();
public void setAge(Integer age);
}
我希望我能用 Groovy 像这样实现它(但我的编译器提示缺少 setter):
public class Cat implements Animal { // Groovy class
public String name;
public Integer age;
}
最佳答案
您可以使用 groovy properties 做到这一点,但要考虑 fields and properties 之间的区别:
A field is a member of a class or a trait which:
- a mandatory access modifier (public, protected, or private)
- one or more optional modifiers (static, final, synchronized)
- an optional type
- a mandatory name
[...]
A property is a combination of a private field and getters/setters. You can define a property with:
- an absent access modifier (no public, protected or final)
- one or more optional modifiers (static, final, synchronized)
- an optional type
- a mandatory name
Groovy will then generate the getters/setters appropriately.
当您放置一个显式访问修饰符时,您实际上是在使用一个字段,因此不会生成 getter/setter,这就是为什么编译器会提示 Can't have an abstract method in a non-abstract class
,因为 getter/setter 不存在。
关于java - 我可以使用 groovy 的默认 getter/setter 来帮助实现 java 接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107148/