Save
prefi
1
Save
Share
Learn
Content
Leaderboard
Learn
Created by
tinlines
Visit profile
Cards (18)
Enumeration
(enum)
A data type that contains a fixed set of
constants
Enums are good to use when you already know all possibilities of the
values
or instances of the
class
With
enums
, it is impossible to create an invalid enum value without introducing a compiler error
Examples of when enumerations are useful
Compass directions
Months
of the year
Cards
in a deck
Creating an enum
1. Declare a
type
with the enum keyword
2. Provide an
identifier
for the type
3. List the enum
constants
Enum constants
The only allowed values for the enum
type
Enum methods
toString
()
ordinal
()
equals
()
compareTo
()
Static enum methods
valueOf
()
values
()
Enums can be declared in their
own file
or within a
class
, but not within a method
Using enums in a switch statement
Displaying pizza prices based on
size
Type-safe
Allows only appropriate
behaviors
Nested class
A class created within another class
Types of nested classes
Static member class
Non-static member class (inner class)
Local
class
Anonymous
class
Reasons for nesting a class
The
inner
class is used only by the
top-level
class
Makes the
connection
between the classes easier to
understand
Makes the code easier to
maintain
Example of a nested class
RealEstateListing
class with a nested
HouseData
class
Inner classes can access their
top-level
class's fields and methods, even if they are
private
Outer
classes can access their
inner
class's members
Nested classes
are not frequently created, but they are seen in some built-in Java
classes