Phoenix
Phoenix

Reputation: 8923

What are 'properties' in Groovy?

Properties in groovy seem like class fields in java without an access modifier. Is that true? Or they have a special meaning. It seems like there is no way to make the properties private?

Upvotes: 18

Views: 24988

Answers (2)

Brian Henry
Brian Henry

Reputation: 3171

Properties can normally be treated like fields, but they are actually backed by implicit getters/setters, so you can still reference them like fields or set them equal to values. Behind the scenes, they are using getters/setters (which you can redefine if you care to).

This page has details on properties/fields and access modifiers (see especially the "Property and field rules" section): https://groovy-lang.org/objectorientation.html#_fields_and_properties

It also shows that you can make a private property (private field backed by private getters/setters), but you have to be explicit in defining the getters/setters.

Upvotes: 6

Andre Steingress
Andre Steingress

Reputation: 4411

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.

class A {
    String property

    /* 
         private String property

         public void setProperty(String property) { ... }
         public String getProperty() { ... }
    */
}

If we declare a public instance variable field we just get a public field, without a setter/getter method pair.

class A {
    public String field

    /* 
         public String field
    */
}

From a Groovy client's pov, there is no difference between accessing a Groovy property and a public field at runtime

def a = new A()
println a.field
println a.property

although a.field accesses the instance variable directly and a.property actually calls a.getProperty() (or a.setProperty(...) when assigning a value). But as the property complies to the JavaBeans spec, the class can seamlessly be used in Java-based environments.

I do not see much sense in making a "private property". private restricts the use of a method or instance/class variable to the hosting class type. But maybe you were referring to making a private field instance variable.

Upvotes: 27

Related Questions