Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 888
SnoopDougg Avatar asked Feb 09 '23 19:02

SnoopDougg


1 Answers

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.

like image 77
jalopaba Avatar answered Apr 06 '23 22:04

jalopaba