I’m learning groovy and I’ve just learned about the new feature added in 2.3, which is the addition of Traits. Now to me it seems like Traits allow you to do basically everything a super-class and an Interface can do.
Does the addition of Traits to Groovy make Inheritance and Interfaces obsolete?
And if not, then what is the best time to use each of these mechanisms?
3
Traits combine the best of both worlds – the inheritance of (abstract) classes and the implementation of interfaces. A trait can contain default implementations of methods and yet a type can implement multiple traits at once. This allows some kind of multiple inheritance, but in a good way, avoiding the deadly diamond of death.
If you don’t know how to start, then use traits. You gain flexibility and can switch to interfaces or class inheritance later on if required.
5