Home >Java >javaTutorial >How to implement composition of classes using mixins, a common technique in Java
When a trait is used in a combined class, it is called a mixin.
<p><code>abstract class A {</code><code> val message: String</code><code>}</code><code>class B extends A {</code><code> val message = "I'm an instance of class B"</code><code>}</code><code>trait C extends A {</code><code> def loudMessage = message.toUpperCase()</code><code>}</code><code>class D extends B with C</code><code><br></code><code>val d = new D</code><code>println(d.message) // I'm an instance of class B</code><code>println(d.loudMessage) // I'M AN INSTANCE OF CLASS B</code></p>
kind
D
There is a parent class
B
and a mix in
C
. A class can only have one parent class but can have multiple mixins (using the keyword
extend
and
with
). Mixins may have the same parent class as a parent class.
Now, let’s look at a more interesting example where an abstract class is used:
abstract class AbsIterator { type T def hasNext: Boolean def next(): T}
There is an abstract type in this class
T
and standard iterator methods.
Next, we will implement a concrete class (all abstract members
T
,
hasNext
and
next
will be implemented):
abstract class AbsIterator { type T def hasNext: Boolean def next(): T }
StringIterator
with a
String
Constructor for type parameters that can be used to iterate over strings. (For example, check whether a string contains a certain character):
Now we create a trait that also inherits from
AbsIterator
.
trait RichIterator extends AbsIterator { def foreach(f: T => Unit): Unit = while (hasNext) f(next()) }
This trait is implemented
foreach
Method - as long as there are still elements to iterate over (
while (hasNext)
), it will always look at the next element (
next()
) calls the passed function
f: T => Unit
. because
RichIterator
It is a trait and does not need to be implemented
AbsIterator
Abstract members in .
Next we need to
StringIterator
and
RichIterator
The functions in are combined into a class.
object StringIteratorTest extends App { class RichStringIter extends StringIterator("Scala") with RichIterator val richStringIter = new RichStringIter richStringIter foreach println }
New class
RichStringIter
There is a parent class
StringIterator
and a mix in
RichIterator
. With single inheritance, we wouldn't have this flexibility.
The above is the detailed content of How to implement composition of classes using mixins, a common technique in Java. For more information, please follow other related articles on the PHP Chinese website!