Dark theme | Light theme

June 14, 2010

Groovy Goodness: Inherit Constructors From Parent Classes

We have a new transformation annotation in Groovy 1.7.3 to safe us a lot of typing when we define new classes that extend from parent classes with multiple constructors: @InheritConstructors. When we apply this transformation to our class we automatically get all constructors from the super class. This is very useful if we for example extend from java.lang.Exception, because otherwise we would have to define four constructors ourselves. The transformation adds these constructors for us in our class file. This works also for our own created classes.

import groovy.transform.InheritConstructors

class MyException extends Exception {

def e = new MyException()
def e1 = new MyException('message')   // Other constructors are available.
assert 'message' == e1.message

class Person {
    String name
    Person(String name) { = name

class Child extends Person {}

def child = new Child('Liam')
assert 'Liam' ==