3

I've seen in several code libraries classes named Mixin with comments like:

//Mixin style implementation
public class DetachableMixin implements Detachable {}

Which is the concept under this style of implementations?

Rehan Javed
  • 418
  • 3
  • 14
Jordi
  • 20,868
  • 39
  • 149
  • 333

3 Answers3

5

Here is a qoute from Joshua Bloch "Efective Java" (I don't think, I could explain it better myself):

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 behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects. Such an interface is called a 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 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.

DanielBK
  • 892
  • 8
  • 23
3

The other answer is spot on, but it might be worth pointing out that other JVM languages go even further.

Scala for examples has traits - basically "interfaces" with method implementations. In scala, you can mix one class together with multiple traits, thereby allowing to inherit behavior from several different "places.

Basically the same concept that Java picked up with Java 8, where you know can add default method behavior to interfaces. And for the record: if I recall it correctly, Java8 interfaces and default methods are not meant to introduce a full "mixin" concept in the Java language. The idea is not that you should use this feature to achieve multiple inheritance through the back door. See this lengthy answer from Stuart Mark, one of the people driving the Java language evolution. They state:

The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

A good article about implementing mixin pattern with Virtual Extension Methods since Java 8: https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/

The virtual extension method is something new in Java. It brings another mean of expression to create new patterns and best pratices. This article provides an example of such a pattern, enabled in Java 8 due to the use of virtual extension methods. I am sure you can extract other new patterns from them. But, as I have experienced here, you should not hesitate to share them in a view to check their validaty.

Sunbreak
  • 391
  • 3
  • 8