How does java combine classes by blending
Today, I would like to share with you how java combines the relevant knowledge points of the class through mixing. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's learn about it.
When a trait is used to combine classes, it is called blending.
Abstract class A {val message: String} class B extends A {val message = "I'm an instance of class B"} trait C extends A {def loudMessage = message.toUpperCase ()} class D extends B with C
Val d = new Dprintln (d.message) / / I'm an instance of class Bprintln (d.loudMessage) / / I'M AN INSTANCE OF CLASS B class D has a parent class B and a blending C. A class can have only one parent class but can have multiple mixings (using the keywords extend and with, respectively). Blending may have the same parent class as a parent class.
Now, let's look at a more interesting example that uses an abstract class: abstract class AbsIterator {type T def hasNext: Boolean def next (): t} with an abstract type 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 a constructor with a String type parameter that can be used to iterate over strings. (for example, to see if a string contains a character): now let's create a trait that also inherits from AbsIterator. Trait RichIterator extends AbsIterator {def foreach (f: t = > Unit): Unit = while (hasNext) f (next ())} this attribute implements the foreach method-- as long as there is an element that can be iterated (while (hasNext)), the incoming function f: t = > Unit is always called on the next element (next ()). Because RichIterator is a feature, you don't have to implement abstract members in AbsIterator. Next we will combine the functions in StringIterator and RichIterator into one class. Object StringIteratorTest extends App {class RichStringIter extends StringIterator ("Scala") with RichIterator val richStringIter = new RichStringIter richStringIter foreach println} the new class RichStringIter has a parent class StringIterator and a blending RichIterator. If it were a single inheritance, we would not achieve such flexibility. These are all the contents of the article "how java combines classes by blending". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.