Java_Magazine_NovemberDecember_2018

(singke) #1

44


//java at present/


In fact, allowing this mix would require adapting the type-checking and overload-resolution
rules. However, this mix is something that might be considered in a future Java version. The
benefit of this restriction for now is that it enforces a consistent style and raises fewer eyebrows
when you look at code.

Nests
Nests are filled with inner classes rather than birds. Let’s look at what nests are and what prob-
lem they solve.
For a long time, Java supported the concept of an inner class—that is, a class that’s con-
tained within another class. Inner classes may be anonymous, which means they do not have a
name. Inner classes were pretty use-
ful before lambda expressions replaced
some of them by defining simple bod-
ies of behavior.
Let’s take a look at a simple exam-
ple of an inner class. Suppose you want
to loop over the characters in a String
in the same way that you can with an
array of char values. To implement this, you need to write a class, StringIterable, that adapts
the String class into the Iterable interface that the for each loop uses, so you can write code
like this:

for (Character character : new StringIterable("abc")) {
System.out.println(character);
}

Internally, your StringIterable class has an iterator() method that returns a new Iterator
object that iterates over the char values in the String. You implement this StringIterator class
as an inner class—for example:

The concept of a nest applies only to
classes syntactically nested within each
o th er. It doesn’t apply to different classes within the
same source file.
Free download pdf