Java Reference
In-Depth Information
No, because traits can be multiple inherited, unlike abstract classes. Java has always had
multiple inheritance of types because a class can implement multiple interfaces. Now Java 8,
through default methods, introduces multiple inheritance of behaviors but still doesn't allow
multiple inheritance of state, something permitted by Scala traits.
To show an example of what a trait looks like in Scala, let's define a trait called Sized that
contains one mutable field called size and one method called isEmpty with a default
implementation:
You can now compose it at declaration time with a class, here an Empty class that always has
size 0:
Interestingly, compared to Java interfaces, traits can also be composed at object instantiation
time (but it's still a compile-time operation). For example, you can create a Box class and decide
that one specific instance should support the operations defined by the trait Sized:
What happens if multiple traits are inherited declaring methods with the same signatures or
fields with the same names? Scala provides restriction rules similar to those you saw with
default methods in chapter 9 .
15.4. Summary
Following are the key concepts you should take away from this chapter:
 
Search WWH ::




Custom Search