Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Classes and Traits

Inheritance and Interfaces in Groovy

Learn Groovy inheritance: extends, super, method overriding, abstract classes, interfaces with default methods, duck typing, multi-methods, enums and casting with instanceof.

Inheritance in Groovy works as in Java: a class can extend one parent, implement many interfaces, override methods and call super. What differs is the dynamic side. Because method calls are resolved at run time, Groovy supports multi-methods and duck typing: if an object has the method you call, it works, regardless of its class. This lesson covers the shared basics and then the Groovy-specific twists.

Groovy code is read-only here; Java stand-ins are runnable.

extends and super

GROOVY
class Animal {
    String name

    String speak() { "..." }

    String describe() { "$name says ${speak()}" }
}

class Dog extends Animal {
    String speak() { 'Woof' }
}

class Puppy extends Dog {
    String speak() { super.speak() + '!' }
}

println new Dog(name: 'Rex').describe()          // Rex says Woof
println new Puppy(name: 'Bit').describe()        // Bit says Woof!

A subclass inherits properties and methods, can override a method by declaring one with the same signature, and can call the parent's version with super. In Groovy overriding needs no annotation (you may add @Override and the compiler will then check that a parent method really exists, which catches typos).

describe() in Animal calls speak(), and the call finds the right version for the actual object: this is polymorphism.

Java Java stand-in: polymorphism

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.

Abstract classes

An abstract class cannot be instantiated and may declare abstract methods that subclasses must implement:

GROOVY
abstract class Shape {
    abstract double area()

    String report() { "${getClass().simpleName} area: ${String.format('%.2f', area())}" }
}

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

class Rect extends Shape {
    double w, h
    double area() { w * h }
}

[new Circle(r: 1), new Rect(w: 2, h: 3)].each { println it.report() }
// Circle area: 3.14
// Rect area: 6.00

The base class holds shared behavior (report), the children supply the missing piece (area). This is the template method pattern.

Interfaces

An interface describes methods without bodies. A class promises to provide them with implements:

GROOVY
interface Payable {
    BigDecimal amount()
}

interface Describable {
    String describe()
}

class Invoice implements Payable, Describable {
    BigDecimal total
    BigDecimal amount() { total }
    String describe() { "Invoice for $total" }
}

Payable p = new Invoice(total: 99.90)
println p.amount()             // 99.90

A class can implement many interfaces. Java 8 default methods are supported in Groovy interfaces (and in Groovy 2.5+ you can declare them), but traits are the more powerful Groovy tool for sharing behavior: see Traits.

Duck typing

Groovy does not demand that an object implement an interface. If the method exists when called, the call works:

GROOVY
class Duck { String quack() { 'Quack!' } }
class Robot { String quack() { 'Beep quack' } }
class Cat { }

def makeNoise(thing) { thing.quack() }

println makeNoise(new Duck())     // Quack!
println makeNoise(new Robot())    // Beep quack
makeNoise(new Cat())              // MissingMethodException

"If it walks like a duck and quacks like a duck, it is a duck." makeNoise accepts any object with a quack() method, with no shared base class. This makes Groovy code flexible and is the reason mocking and testing are easy. The price: mistakes show up when the line runs, not when you compile. Type checking with @TypeChecked or @CompileStatic brings compile-time safety back, at the cost of duck typing (unless you declare the interface).

The stand-in below shows duck typing with reflection, which is what Groovy does automatically.

Java Java stand-in: duck typing via reflection

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.

Multi-methods

When methods are overloaded, Groovy picks the one that fits the runtime types of the arguments. In Java the declared type decides.

GROOVY
class Printer {
    String show(Object o) { 'object' }
    String show(String s) { 'string' }
    String show(Integer i) { 'integer' }
}

Object value = 'hello'
println new Printer().show(value)       // string  (Java would say: object)
println new Printer().show(42)          // integer
println new Printer().show(3.5)         // object  (no better match)

This is also the basis of the visitor pattern without a visitor class: a method visit(Circle) and visit(Square) in one class are dispatched from a generic Shape variable. Under @CompileStatic, Groovy behaves like Java again and uses the declared type.

Type tests and casting

GROOVY
def x = 'text'
if (x instanceof String) { println x.size() }
def y = x as String                      // coercion
def n = (Number) 5                       // plain cast: fails if not a Number
println (x in String)                    // true (isCase on a class)

instanceof works as in Java. In dynamic code you rarely need to cast, since method calls are resolved on the real object.

Enums

Enums are Java enums with Groovy conveniences:

GROOVY
enum Level {
    LOW(1), MEDIUM(5), HIGH(10)

    final int weight
    Level(int weight) { this.weight = weight }
    boolean urgent() { this == HIGH }
}

println Level.MEDIUM.weight         // 5
println Level.values()*.name()      // [LOW, MEDIUM, HIGH]
println Level.valueOf('HIGH').urgent()  // true

switch (Level.LOW) {
    case Level.LOW: println 'quiet'; break
}

Enums work as switch cases and map keys, and Level.values() returns them in declaration order. The statement Level level = 'HIGH' even coerces a string into an enum constant.

Final classes, methods and @Override

Use final to prevent overriding or subclassing, as in Java, and @Override to let the compiler catch mistakes in names or signatures. A frequent bug in dynamic code is a misspelled override (speek()), which silently adds a new method; @Override turns it into a compile error.

Composition over inheritance

Deep hierarchies get brittle. Prefer small interfaces and traits (next lesson), and the @Delegate annotation to forward calls to an inner object without writing each method.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which keyword calls the parent class's version of an overridden method?

    super.method() calls the parent's implementation, as in Java.
  2. 2. What is duck typing?

    If the object has the method at run time, the call works. No common interface or superclass is required.
  3. 3. With overloads show(Object) and show(String), what does Object v = 'hi'; show(v) call in dynamic Groovy?

    Groovy dispatches on the runtime types of the arguments (multi-methods).
  4. 4. Why add @Override to an overriding method?

    @Override catches typos and wrong signatures at compile time.

Summary

  • Use extends, implements, super and abstract as in Java.
  • Duck typing lets any object with the right method be used; add type checking when you want safety.
  • Multi-methods dispatch on runtime argument types; @CompileStatic reverts to Java's rules.
  • Enums can carry fields and methods and work with switch.
  • Prefer composition, traits and @Delegate to deep hierarchies.

Next: Traits