Methods in Groovy

Groovy supports methods defined on class types.

class Rectangle {
    int width
    int height

    // This area method is defined on the Rectangle class
    int area() {
        return width * height
    }

    // Methods can be defined for the class directly
    int perimeter() {
        return 2 * width + 2 * height
    }
}

def r = new Rectangle(width: 10, height: 5)

// Here we call the 2 methods defined for our class
println("area: ${r.area()}")
println("perimeter: ${r.perimeter()}")

// Groovy automatically handles method calls on references
def rp = r
println("area: ${rp.area()}")
println("perimeter: ${rp.perimeter()}")

Output:

area: 50
perimeter: 30
area: 50
perimeter: 30

In Groovy, methods are defined within classes. Unlike some other languages, Groovy doesn’t have a separate concept of “receiver types” for methods. Instead, methods are always associated with the class they’re defined in.

The area() and perimeter() methods are defined directly in the Rectangle class. They can access the instance variables (width and height) directly.

In the main part of the script, we create an instance of Rectangle using Groovy’s convenient map-style constructor syntax. We then call the methods on this instance.

Groovy uses duck typing and doesn’t distinguish between calling methods on values or references. This is why we can call the same methods on both r and rp with the same results.

Groovy’s approach to object-oriented programming is more traditional compared to some other languages, but it offers a lot of syntactic sugar and dynamic features that make it very expressive and flexible.

Next, we’ll look at Groovy’s mechanism for defining interfaces, which are used to specify a set of methods that a class must implement.