Classes and Traits

Site Admin · 11 Sep 2026 · 7 views

Groovy Classes

Groovy classes follow Java conventions but with less boilerplate. Properties are auto-generated, and common methods like toString() and equals() are provided automatically.

Simple Classes

class Person {
    String name
    int age
}

// Named parameter constructor
def person = new Person(name: "Alice", age: 30)

// toString() is auto-generated
println person  // Person(Alice, 30)

Traits

Traits are Groovy's version of interfaces with default implementations. They support both state and behavior:

trait Greetable {
    String greeting = "Hello!"

    void greet() {
        println greeting
    }
}

trait Swimmable {
    void swim() {
        println "Swimming..."
    }
}

class Dolphin implements Greetable, Swimmable {
    String name
}

new Dolphin(name: "Flipper").greet()  // Hello!

Multiple Inheritance

Traits allow a form of multiple inheritance that Java interfaces cannot provide:

trait A {
    String hello() { "Hello from A" }
}

trait B {
    String hello() { "Hello from B" }
}

class C implements A, B {
    // Must override to resolve conflict
    String hello() { "Hello from C" }
}

Abstract Classes

Groovy abstract classes work identically to Java:

abstract class Shape {
    abstract double area()
    String describe() { "Area: ${area()}" }
}

class Circle extends Shape {
    double radius
    double area() { Math.PI * radius * radius }
}

Key Points

  • Groovy auto-generates toString(), equals(), and hashCode().
  • Properties auto-generate getters and setters.
  • Traits provide interfaces with default implementations and state.
  • Traits support multiple inheritance with conflict resolution.
  • Abstract classes work the same as in Java.
Share this post:

Comments (0)

Please login or register to comment.