Java Reference
In-Depth Information
When each element of the enum is declared, you have to denote the argument for the
constructor within parentheses. This invokes the constructor on line 6, which stores the
value in the scoops fi eld of each element in the IceCream enum.
Study the following code and determine its output:
IceCream cone1 = IceCream.PLAIN;
IceCream cone2 = IceCream.WAFFLE;
System.out.println(cone1 + “ needs “ + cone1.scoops + “ scoops.”);
System.out.println(cone2 + “ needs “ + cone2.scoops + “ scoops.”);
The output is shown here:
PLAIN needs 2 scoops.
WAFFLE needs 5 scoops.
Declaring Nested Classes
The exam objectives state that you need to be able to “develop code that declares classes
(including all forms of nested classes).” A nested class is a class defi ned within another
class. A nested class that is nonstatic is referred to as an inner class . There are four types of
nested classes in Java:
A member inner class is a nonstatic nested class that is declared at the member level of
a class.
A local inner class is defined within a method. Because it appears within a method,
making it static does not make sense.
An anonymous inner class is a special case of a local inner class that does not have a
name.
Top -level inner classes are static inner classes that are nested at the member level of a
class.
The concept of inner classes was introduced in Java 1.1. There are several benefi ts of
using inner classes, including making your code more readable, allowing for utility classes
to be encapsulated within the class using it, and simplifying the process of writing a class,
thereby actually encouraging developers to be more object oriented. (The easier it is to
write a class, the more likely you are to use classes!) This section discusses the details of
declaring and using the four different types of nested classes.
Member Inner Classes
A member inner class is defi ned at the member level of a class (the same level as fi elds,
methods and constructors). Member inner classes have the following properties:
Search WWH ::




Custom Search