Java Reference
In-Depth Information
Java Mixins: Mixing in Methods
Problem
You've heard about “mixins” and want to apply them in Java.
Solution
Use static imports. Or, declare one or more functional interfaces with a “default” method
containing the code to execute, and simply implement it.
Discussion
Developers from other languages sometimes deride Java for its inability to handle “mixins,”
the ability to “mix in” bits of code from other classes.
One way to implement mixins is with the “static import” feature, which has been in the lan-
guage for a decade. This is often done in Unit Testing (see Avoiding the Need for Debuggers
with Unit Testing ) . A limitation of this approach is that, as the name implies, the methods
must be static methods, not instance methods.
A newer mechanism depends on an interesting bit of fallout from the Java 8 language
changes in support of lambdas: you can now “mix in” code from unrelated places into one
class. Has Java finally abandoned its staunch opposition to multiple inheritance? It may seem
that way when you first hear it, but relax: you can only pull methods from multiple inter-
faces, not from multiple classes. If you didn't know that you could have methods defined
Search WWH ::




Custom Search