Java Reference
In-Depth Information
8.1 Introduction
8.2 Time Class Case Study
8.3 Controlling Access to Members
8.4 Referring to the Current Object's
Members with the this Reference
8.5 Time Class Case Study: Overloaded
Constructors
8.6 Default and No-Argument
Constructors
8.7 Notes on Set and Get Methods
8.8 Composition
8.9 enum Types
8.10 Garbage Collection
8.11 static Class Members
8.12 static Import
8.13 final Instance Variables
8.14 Package Access
8.15 Using BigDecimal for Precise
Monetary Calculations
8.16 (Optional) GUI and Graphics Case
Study: Using Objects with Graphics
8.17 Wrap-Up
Summary | Self-Review Exercise | Answers to Self-Review Exercise | Exercises | Making a Difference
8.1 Introduction
We now take a deeper look at building classes, controlling access to members of a class and
creating constructors. We show how to throw an exception to indicate that a problem has
occurred (Section 7.5 discussed catch ing exceptions). We use the this keyword to enable
one constructor to conveniently call another constructor of the same class. We discuss
composition —a capability that allows a class to have references to objects of other classes as
members. We reexamine the use of set and get methods. Recall that Section 6.10 intro-
duced the basic enum type to declare a set of constants. In this chapter, we discuss the re-
lationship between enum types and classes, demonstrating that an enum type, like a class,
can be declared in its own file with constructors, methods and fields. The chapter also dis-
cusses static class members and final instance variables in detail. We show a special re-
lationship between classes in the same package. Finally, we demonstrate how to use class
BigDecimal to perform precise monetary calculations. Two additional types of classes—
nested classes and anonymous inner classes—are discussed in Chapter 12.
8.2 Time Class Case Study
Our first example consists of two classes— Time1 (Fig. 8.1) and Time1Test (Fig. 8.2).
Class Time1 represents the time of day. Class Time1Test 's main method creates one object
of class Time1 and invokes its methods. The output of this program appears in Fig. 8.2.
Time1 Class Declaration
Class Time1 's private int instance variables hour , minute and second (lines 6-8) repre-
sent the time in universal-time format (24-hour clock format in which hours are in the
range 0-23, and minutes and seconds are each in the range 0-59). Time1 contains public
methods setTime (lines 12-25), toUniversalString (lines 28-31) and toString (lines
34-39). These methods are also called the public services or the public interface that the
class provides to its clients.
 
 
 
Search WWH ::




Custom Search