Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Mixin implementation classes

Tags:

java

mixins

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?

like image 565
Jordi Avatar asked Jul 16 '26 06:07

Jordi


2 Answers

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.

like image 184
DanielBK Avatar answered Jul 17 '26 20:07

DanielBK


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.

like image 41
GhostCat Avatar answered Jul 17 '26 20:07

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!