Search code examples
javamixins

An example of a mixin in Java?


On page 93-4 of Effective Java, I came across the term mixin. But I am finding it difficult to visualise what a mixin actually is. Could anybody please help me out by providing an example of a mixin in Java?


Solution

  • You're referring to Item 18 of Effective Java - Prefer interfaces to abstract classes, and I believe the following section in particular:

    Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behaviour. For exampleComparable is a mixin interface that allows a class to declare that it its instances are ordered with respect to other mutually comparable objects. Such an interface is called mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality. Abstract classes can't be used to define mixins for the same reason that they can't be be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

    Essentially, one of the key differences between specifying functionality in an abstract class and in an interface is that the interface version can be used in a number of different class hierarchies, whereas an abstract class can only be used in the one class hierarchy tree because Java only allows single-inheritance.