Mixins and traits

The developers of the Java language were well-versed in C++ and other languages that include multiple inheritance, whereby classes can inherit from an arbitrary number of parents. One of the problems with multiple inheritance is that it's impossible to determine which parent inherited functionality is derived from. This problem is called the diamond problem. The diamond problem and other complexities that are inherent in multiple inheritance inspired the Java language designers to opt for single inheritance plus interfaces.

Interfaces define semantics but not behavior. They work well for defining method signatures and data abstractions, and all of the languages support Java interfaces with no essential changes. However, some cross-cutting concerns don't fit into a single-inheritance-plus-interfaces model. This misalignment led to the necessity of external mechanisms for the Java language such as aspect-oriented programming. Two of the languages — Groovy and Scala — handle such concerns at another level of extension by using a language construct called a mixin or trait. This article explains Groovy mixins and Scala traits and shows how to use them.

Read more on IBM developerWorks...

This story, " Mixins and traits" was originally published by JavaWorld.

Copyright © 2013 IDG Communications, Inc.