patternModerate
Constructors and inheritance in Groovy
Viewed 0 times
andconstructorsinheritancegroovy
Problem
I am new to Groovy and I am having a little problem with constructors of subclasses. Basically, I have a base abstract class like
and a bunch of derived classes like
I would like to be able to create instances like
Unfortunately, Groovy creates automatically all sorts of constructors for
It feels repetitive doing so for each subclass, and it is probably the wrong way.
What would be the Groovy way to share some logic in the constructor?
class BaseClass {
def BaseClass(Map options) {
// Does something with options,
// mainly initialization.
}
// More methods
}and a bunch of derived classes like
class AnotherClass extends BaseClass {
// Does stuff
}I would like to be able to create instances like
def someObject = new AnotherClass(foo: 1, bar: 2)Unfortunately, Groovy creates automatically all sorts of constructors for
AnotherClass, with various signatures - based on the properties of AnotherClass - but will not allow me to just reuse the constructor in BaseClass. I have to manually create one likeclass AnotherClass extends BaseClass {
def AnotherClass(options) {
super(options)
}
// Does stuff
}It feels repetitive doing so for each subclass, and it is probably the wrong way.
What would be the Groovy way to share some logic in the constructor?
Solution
@InheritConstructors is probably what you are looking for:@InheritConstructors
class AnotherClass extends BaseClass {}will create the constructors corresponding to the superclass constructors for you.
Code Snippets
@InheritConstructors
class AnotherClass extends BaseClass {}Context
StackExchange Code Review Q#13696, answer score: 19
Revisions (0)
No revisions yet.