An example of a mixin in Java?

In 'Effective Java'`s scope, it is mentioned just logically, without specific Java implementation. For example, a Comparable interface. It doesn't change your class purpose or confuse your api users. It just mixes in functionality for sorting and comparation. So, in a Java context I would narrow this to a Decorator pattern.

Another variation on a mix-in could be the following. Assume, you have:

interface IMyInterface
{
    public void doStuff();
}

class MyClass implements IMyInterface
{
    public void doStuff(){};
}

Now we want to 'mix in' some additional functionality. We add an abstract class:

abstract class AbstractMixInProvider
{
    public abstract void doMixinStuff();
}

And we extend MyClass from AbstractMixInProvider:

class MyClass extends AbstractMixInProvider implements IMyInterface
{
    public void doStuff(){};
    public void doMixinStuff();
}

But, as I`ve mentioned above, trying to pull mix-in concept to Java looks ugly, because it is just play on words.


There is no such thing as mix-in in java since there's no way to add the a piece of code to classes in separate hierarchies. To do so would require multiple inheritance or a least Scala type traits.


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.

Tags:

Java