Interfaces in Groovy

Interfaces are named collections of method signatures in Groovy. Here’s an example demonstrating the concept:

// Here's a basic interface for geometric shapes.
interface Geometry {
    double area()
    double perim()
}

// For our example we'll implement this interface on
// Rectangle and Circle classes.
class Rectangle implements Geometry {
    double width
    double height

    Rectangle(double width, double height) {
        this.width = width
        this.height = height
    }

    // To implement an interface in Groovy, we just need to
    // implement all the methods in the interface.
    double area() {
        return width * height
    }

    double perim() {
        return 2 * width + 2 * height
    }

    String toString() {
        "Rectangle(width: $width, height: $height)"
    }
}

class Circle implements Geometry {
    double radius

    Circle(double radius) {
        this.radius = radius
    }

    double area() {
        return Math.PI * radius * radius
    }

    double perim() {
        return 2 * Math.PI * radius
    }

    String toString() {
        "Circle(radius: $radius)"
    }
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic measure function taking advantage of this
// to work on any Geometry.
def measure(Geometry g) {
    println g
    println g.area()
    println g.perim()
}

// Main execution
def r = new Rectangle(3, 4)
def c = new Circle(5)

// The Circle and Rectangle classes both
// implement the Geometry interface so we can use
// instances of these classes as arguments to measure.
measure(r)
measure(c)

To run this Groovy script, save it to a file (e.g., interfaces.groovy) and execute it using the groovy command:

$ groovy interfaces.groovy
Rectangle(width: 3.0, height: 4.0)
12.0
14.0
Circle(radius: 5.0)
78.53981633974483
31.41592653589793

In this example, we’ve defined an interface Geometry and implemented it in two classes: Rectangle and Circle. The measure function demonstrates how we can use interface types to work with different implementations in a uniform way.

Groovy’s implementation of interfaces is similar to Java’s, but with some added syntactic sugar and dynamic features. The implements keyword is used to declare that a class implements an interface, and all methods defined in the interface must be implemented in the class.

Interfaces in Groovy provide a powerful way to define contracts that classes must adhere to, enabling polymorphism and promoting loose coupling in your code.