Java 8 — Just a little “explanation” 2

In the first part of this sequence you saw a new method on our List, the forEach. But, until Java 7 this method didn’t existed… how did it happen?

We know that if this method would be declared in an interface, we could have a big problem! What?

Everyone who implemented the interface would need to implement it.
Chaos would be installed, work would be immense, the Java community would go insane.
An interface like List would destroy libraries used by most of us, such as Hibernate.

Would be welcome to “NoSuchMethodErrors” Hell

BUT … we get a new feature in Java 8!

Default Methods

With this feature we can add a method to an interface and ensure that all implementations have it implemented. 🙂

For example, the forEach method we use is declared inside java.lang.Iterable, which is the parent of Collection, in turn List’s parent.

If we look at the method in the interface we’ll find:

default void forEach(Consumer <? Super T> action) {
   Objects.requireNonNull (action);
   for (T t: this) {
      action.accept (t);
   }
}

Yes, I think you never expected that, method with code inside interfaces..

As ArrayList implements List, which is (indirect) daughter of Iterable,
The ArrayList has this method, whether it wants to or not. It is for this reason that we can do it:

books.forEach(b -> System.out.println(b.getName()));

This reading serves as an explanation for the first part, which used this new feature.

Bye bye, see you!

References:
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Published by Ivan Marrêta

Software Engineer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: