Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Classes and Traits

Classes and Properties in Groovy

Learn how to write Groovy classes (POGOs): properties versus fields, generated getters and setters, custom accessors, visibility, static members, packages, and a safe way to read fields.

In Java, a simple data class needs fields, a constructor, getters, setters, equals, hashCode and toString: dozens of lines for two values. Groovy classes, often called POGOs (Plain Old Groovy Objects), remove nearly all of that. You declare a property and Groovy supplies the field, the getter and the setter. This lesson explains how properties work, how to customise them, and how visibility, static members and methods behave.

Groovy code is read-only here. Java stand-ins show what Groovy generates for you, and they run.

Your first class

GROOVY
class Person {
    String name
    int age

    String greet() {
        "Hi, I'm $name and I'm $age"
    }
}

def p = new Person(name: 'Ada', age: 36)
println p.greet()          // Hi, I'm Ada and I'm 36
p.age = 37                 // calls setAge(37)
println p.age              // 37, calls getAge()

There is no public (everything is public by default), no semicolons, no getters or setters, and a free named-argument constructor: new Person(name: 'Ada', age: 36). Groovy files may hold several classes, and the file name need not match a class name (although it is a good habit when the file has one public class).

Properties versus fields

A property is declared without an access modifier. A field is declared with one (private, protected, public).

GROOVY
class Account {
    String owner            // property: private field + public getOwner/setOwner
    private double balance  // field: no accessors, visible only in the class
    public String note      // public field
    final String id = 'A-1' // read-only property: getter only
}

When you write account.owner from outside, Groovy calls getOwner(). Inside the class, owner is the same property access; use this.@owner for the raw field. The compiler generates these accessors as real methods, so Java code can call getOwner() as usual.

Java Java stand-in: what Groovy generates for a property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Custom getters and setters

If you define getX() or setX() yourself, Groovy uses yours instead of generating them. That is how you add validation or computed properties:

GROOVY
class Temperature {
    private double celsius

    double getCelsius() { celsius }

    void setCelsius(double value) {
        if (value < -273.15) throw new IllegalArgumentException('below absolute zero')
        celsius = value
    }

    double getFahrenheit() { celsius * 9 / 5 + 32 }     // computed property
}

def t = new Temperature()
t.celsius = 100
println t.fahrenheit        // 212.0

t.fahrenheit looks like a field, but runs getFahrenheit(). There is no fahrenheit field: this is a read-only computed property.

Inside a class, this.name = x calls the setter, but a bare name = x inside the same class assigns the field directly. If you need validation to run, call setName(x) or this.name = x.

Visibility

Modifier Meaning
none (on a property) Property: field plus public accessors
public Public field (rarely used)
protected Class, subclasses and package
private Declaring class only (but see the warning)

Groovy does not strictly enforce private. A caller can often reach private fields and methods at run time (obj.secret), because dynamic dispatch ignores the modifier. Treat private as a strong signal to humans and to static compilation (@CompileStatic), not as a security boundary.

Methods

GROOVY
class Calculator {
    int add(int a, int b) { a + b }
    def twice(x) { x * 2 }                  // dynamic types
    static int max(int a, int b) { a > b ? a : b }
    int sum(int... values) { values.sum(0) }   // varargs
    String describe(String label = 'result', int n = 0) { "$label: $n" }
}

println new Calculator().add(2, 3)          // 5
println Calculator.max(4, 9)                // 9
println new Calculator().describe()         // result: 0

Methods return the last expression, can have default values, and are public unless marked otherwise. Call a method on null and you get a NullPointerException; use ?. to avoid it.

Static members and constants

GROOVY
class Config {
    static final String VERSION = '1.0'
    static int instances = 0

    Config() { instances++ }
}

new Config(); new Config()
println Config.instances       // 2
println Config.VERSION         // 1.0

A static initializer block runs once: static { println 'loaded' }. An instance initializer { ... } runs for every new object before the constructor body.

Accessing properties dynamically

Since property access is just a method call, you can build the name at run time, and you can treat an object like a map for reading:

GROOVY
def p = new Person(name: 'Ada', age: 36)
def field = 'name'
println p."$field"             // Ada   (dynamic property name)
println p['age']               // 36
println p.properties.keySet()  // includes name, age and class
p.setProperty('age', 40)
println p.getProperty('age')   // 40

Properties also respect the safe navigation operator: p?.name. And person.metaClass.properties lists the property definitions, which is the basis for many Groovy libraries that map objects to JSON or databases.

toString, equals and hashCode

A plain POGO prints like Person@1b2c3d and compares by identity. Override the methods, or let an annotation write them (next lessons):

GROOVY
class Point {
    int x, y
    String toString() { "($x, $y)" }
    boolean equals(Object o) { o instanceof Point && o.x == x && o.y == y }
    int hashCode() { [x, y].hashCode() }
}
assert new Point(x: 1, y: 2) == new Point(x: 1, y: 2)

Because == calls equals, the assertion passes. This is much less error-prone than Java where == would compare references. The annotation @EqualsAndHashCode removes this boilerplate (AST Transformations).

Java Java stand-in: equals, hashCode and toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Inner and anonymous classes

Groovy supports inner classes and anonymous classes, as Java does:

GROOVY
def runner = new Runnable() {
    void run() { println 'anonymous class' }
}
runner.run()

In practice a closure is usually shorter: Runnable r = { println 'closure' }.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does String name (no modifier) inside a Groovy class declare?

    Without an access modifier, Groovy creates a property: a field plus public getName() and setName().
  2. 2. What happens when you write t.fahrenheit and the class defines double getFahrenheit() but no field?

    Property access calls the getter, so a getter alone is enough to create a read-only computed property.
  3. 3. How do you read the raw field named owner, bypassing the getter?

    The .@ operator accesses the field directly.
  4. 4. What does == do for two POGO instances that define equals?

    In Groovy == calls equals (or compareTo). Use is() for identity.

Summary

  • A property (no modifier) generates a private field plus getter and setter; a field has an explicit modifier.
  • Define getX/setX yourself to add validation or to create computed properties.
  • Members are public by default; private is advisory at run time.
  • Static members, default arguments and varargs work like Java with less typing.
  • == means equals, so define equals, hashCode and toString (or use annotations).

Next: Constructors and Named Arguments