Java Reference
In-Depth Information
No language feature is always good or always bad. Many would argue that the real issue is
multiple inheritance of state rather than just blocks of code, and as default methods avoid
multiple inheritance of state, they avoid the worst pitfalls of multiple inheritance in C++.
It can also be very tempting to try and work around these limitations. Blog posts have
already cropped up trying to implement full-on traits with multiple inheritance of state as
well as default methods. Trying to hack around the deliberate restrictions of Java 8 puts us
back into the old pitfalls of C++.
It's also pretty clear that there's still a distinction between interfaces and abstract classes. In-
terfaces give you multiple inheritance but no fields, while abstract classes let you inherit
fields but you don't get multiple inheritance. When modeling your problem domain, you
need to think about this tradeoff, which wasn't necessary in previous versions of Java.
Static Methods on Interfaces
We've seen a lot of calling of Stream.of but haven't gotten into its details yet. You may re-
call that Stream is an interface, but this is a static method on an interface. This is another
new language change that has made its way into Java 8, primarily in order to help library de-
velopers, but with benefits for day-to-day application developers as well.
An idiom that has accidentally developed over time is ending up with classes full of static
methods. Sometimes a class can be an appropriate location for utility code, such as the Ob-
jects class introduced in Java 7 that contained functionality that wasn't specific to any par-
ticular class.
Of course, when there's a good semantic reason for a method to relate to a concept, it should
always be put in the same class or interface rather than hidden in a utility class to the side.
This helps structure your code in a way that's easier for someone reading it to find the relev-
ant method.
For example, if you want to create a simple Stream of values, you would expect the method
to be located on Stream . Previously, this was impossible, and the addition of a very
interface-heavy API in terms of Stream finally motivated the addition of static methods on
interfaces.
Search WWH ::




Custom Search