Interface Implementation & Inheritance

In Groovy, an interface is an abstract data type used to define a set of method signatures without providing their implementations. Interfaces define a set of specifications that describe the behavior that a class or object should possess. A class can implement one or more interfaces and provide concrete implementations for the methods defined within them.

The following example demonstrates how to define an interface and implement it in Groovy:

interface Shape {
    double getArea()
    double getPerimeter()
}

class Circle implements Shape {
    double radius
  
    Circle(double radius) {
        this.radius = radius
    }
  
    double getArea() {
        Math.PI * radius * radius
    }
  
    double getPerimeter() {
        2 * Math.PI * radius
    }
}

def circle = new Circle(5)
println("Area: ${circle.getArea()}") // Output: "Area: 78.53981633974483"
println("Perimeter: ${circle.getPerimeter()}") // Output: "Perimeter: 31.41592653589793"

In the example above, we define a Shape interface with two methods: getArea and getPerimeter. Subsequently, we define a Circle class that implements the Shape interface. The Circle class possesses a property named radius and provides implementations for both methods defined in the Shape interface. We then instantiate a Circle object, invoke the getArea and getPerimeter methods, and output the calculated area and perimeter of the circle.

Groovy also supports interface inheritance, where an interface can inherit one or more other interfaces and define constants within itself. Similar to interfaces in Java, Groovy interfaces allow for default method implementations, which facilitates writing classes that implement these interfaces.