1. Nested Types
In the previous examples, we always had exactly one type declaration in each file, so-called compilation unit. However, Java also allows for nested types, where a type declaration can be placed inside another type declaration, making the relationship between them even closer. The following exercises demonstrate the usefulness of nested types, but there are also some potential issues that need to be considered. To gain a deeper understanding of nested types, several quizzes will be provided.
Prerequisites
know static nested types
know inner types (non-static nested types)
know local (inner) types
know anonymous inner class
1.1. Declare nested types.
Nested types are useful whenever the inner type has a tight coupling to the outer type, or when a type declaration should be kept "secret" because it should not be visible to other types or even other methods. The next two tasks show examples for exactly these two reasons.
1.1.1. Set AM-FM modulation to radio type. ⭐
In the assignment "Giving radio an AM-FM modulation" from the previous chapter "Writing your own classes" we declared the enumeration type Modulation
, in a separate Java file. The declaration looked like this:
public enum Modulation { AM, FM }
The sound waves with the tones are modulated, resulting in radio waves, which the radio receives and translates back into sound waves. Since a radio always requires modulation, the type Modulation
can be placed in the type Radio
and thus this tight coupling can be well represented with nested types. For example, this makes it easy to separate the modulation of sound waves of a radio from the modulation of a video signal; such a second enumeration could be placed in a class TV
.
Task:
Put the enumeration type
Modulation
in the classRadio
.When we call
setModulation(…)
on a radio, how is AM/FM qualified and passed?
1.1.2. Write three kinds of Watt-Comparator implementations ⭐
In the previous chapter, "Writing your own classes", we implemented the interface Comparator
in the exercise "Comparing consumption of electrical appliances" . As a reminder:
import java.util.Comparator;
public class ElectronicDeviceWattComparator
implements Comparator<ElectronicDevice> {
@Override
public int compare( ElectronicDevice ea1,
ElectronicDevice ea2 ) {
System.out.println( ea1 + " is compared with " + ea2 );
return Integer.compare( ea1.getWatt(), ea2.getWatt() );
}
}
The implementation of the interface is in its own compilation unit, but the interface can also be implemented more locally using nested types.
Task:
Write the
ElectronicDeviceWattComparator
once as astatic nested class,
local class,
anonymous inner class.