Can I use groovy's default getters / setters to help implement a java interface?

 ̄綄美尐妖づ 提交于 2019-12-10 20:03:49

问题


I am extending a very simple Java interface from an imported library. The interface is so simple that the only methods it declares are getters and setters for a list of properties.

My application is written in Groovy, so I'd like to implement this Java interface with a Groovy class.

I was under the impression that Groovy created getters and setters by default for any of its classes' properties - can I use these default getters and setters to satisfy the Java interface's requirements?

Library's Java interface:

public interface Animal {  // java interface
    public String getName();
    public void setName(String name);
    public Integer getAge();
    public void setAge(Integer age);
}

I hoped I'd be able to implement it like this with Groovy (but my compiler is complaining about missing setters):

public class Cat implements Animal { // Groovy class
    public String name;
    public Integer age;
}

回答1:


You can do that with groovy properties, but take into account the difference between 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.

When you put an explicit access modifier, you are actually using a field, so getters/setters are not generated and that's why the compiler complains about Can't have an abstract method in a non-abstract class, since getters/setters are not there.



来源:https://stackoverflow.com/questions/33107148/can-i-use-groovys-default-getters-setters-to-help-implement-a-java-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!