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?
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 example Comparable is a mixin interface that allows a class to declare that it its instances are ordered with respect to other mutually comparable objects.
A mixin is a class (interface, in WebAPI spec terms) in which some or all of its methods and/or properties are unimplemented, requiring that another class or interface provide the missing implementations.
As defined in Wikipedia, a mixin is a class containing methods that can be used by other classes without a need to inherit from it. In other words, a mixin provides methods that implement a certain behavior, but we do not use it alone, we use it to add the behavior to other classes.
Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes. A mixin class acts as the parent class, containing the desired functionality.
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 example
Comparable
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With