Chapter 3
Using Classes and
Objects
Outline
Last Time:
Creating Objects
The GregorianCalendar Class
The String Class
Wrapper Classes
Packages
Math Class
Formatting Output
Enumerated Types
© 2004 Pearson Addison-
3-2
Class Libraries
•
A class library is a collection of classes that we can use
when developing programs
•
The Java standard class library is part of any Java
development environment
•
Its classes are not part of the Java language per se, but we
rely on them heavily
•
Various classes we've already used (System , Scanner,
String) are part of the Java standard class library
•
Other class libraries can be obtained through third party
vendors, or you can create them yourself
© 2004 Pearson Addison-
3-3
Packages
•
The classes of the Java standard class library are organized
into packages
•
Some of the packages in the standard class library are:
Package
Purpose
java.lang
General support
java.applet
Creating applets for the web
java.awt
Graphics and graphical user interfaces
javax.swing
Additional graphics capabilities
java.net
Network communication
java.util
Utilities
javax.xml.parsers
XML document processing
© 2004 Pearson Addison-
3-4
The import Declaration
•
When you want to use a class from a package, you could use
its fully qualified name
java.util.Scanner
•
Or you can import the class, and then use just the class
name
import java.util.Scanner;
•
To import all classes in a particular package, you can use
the * wildcard character
import java.util.*;
© 2004 Pearson Addison-
3-5
The import Declaration
•
All classes of the java.lang package are imported
automatically into all programs
•
It's as if all programs contain the following line:
import java.lang.*;
•
That's why we didn't have to import the System or String
classes explicitly in earlier programs
•
The Scanner class, on the other hand, is part of the
java.util package, and therefore must be imported
© 2004 Pearson Addison-
3-6
Outline
Packages
Math Class
Formatting Output
Enumerated Types
© 2004 Pearson Addison-
3-7
The Math Class
•
The Math class is part of the java.lang package
•
The Math class contains methods that perform various
mathematical functions
•
These include:
absolute value
square root
exponentiation
trigonometric functions
generate random numbers
© 2004 Pearson Addison-
3-8
The Math Class
•
The methods of the Math class are static methods (also
called class methods)
•
Static methods can be invoked through the class name – no
object of the Math class is needed
value = Math.cos(90) + Math.sqrt(delta);
•
See Quadratic.java (page 129)
discriminant
root1 = ((-1
(2 *
root2 = ((-1
(2 *
•
= Math.pow(b, 2) - (4 * a * c);
* b) + Math.sqrt(discriminant)) /
a);
* b) - Math.sqrt(discriminant)) /
a);
We discuss static methods further in Chapter 6
© 2004 Pearson Addison-
3-9
Math Methods
Method
Purpose
Argument
abs(x)
Returns the absolute
value of x
any numeric type same as
argument
ceil(x)
Returns smallest
whole number >= x
double
double
exp(x)
Returns ex where e =
2.71828…
double
double
floor(x)
Returns the largest
whole number <= x
double
double
log(x)
Returns the natural
logarithm of x (base e)
for x > 0.0
double
double
© 2004 Pearson Addison-
Result Type
3-10
Math Methods
Method
Purpose
Argument
max(x,y)
Returns the larger of x
and y
any numeric type same as
argument
min(x,y)
Returns the smaller of
x and y
any numeric type same as
argument
pow(x,y)
Returns xy. An error
any numeric type double
will occur if x = 0 and y
<=0, or x < 0 and y is
not a whole number
random()
Returns a
pseudorandom
number between 0.0
and 1.0
© 2004 Pearson Addison-
double
Result Type
double
3-11
Math Methods
Method
Purpose
Argument
Result Type
rint(x)
Returns the closest
whole number to x
double
double
round(x)
Returns the integer
value closet to x
double or float
long or int
sqrt(x)
Returns the positive
square root of x for
x > 0.0
double
double
© 2004 Pearson Addison-
3-12
Equations
4 3
V = πr
3
• Volume of a sphere
• Kepler’s Law
a 3 GM
=
2
p
4π 2
2
GMp
a=3
4π 2
where a = radius of orbit, p = period of orbit, G = gravity
x = 10
• Brightness of stars
© 2004 Pearson Addison-
( m2 − m1 )
∆m = 2.5 log10 x
3-13
rLat
Equations
•
radius of a circle of latitude rlat = rE cos Θ
•
distance between two points dist =
•
Simulating the rolling of a die – random number
between 1 and 6
© 2004 Pearson Addison-
Θ
r
( x2 − x1 ) 2 + ( y2 − y1 ) 2
3-14
Outline
Packages
Math Class
Formatting Output
Enumerated Types
© 2004 Pearson Addison-
3-15
Formatting Output
•
It is often necessary to format values in certain ways so
that they can be presented properly
•
The Java standard class library contains classes that
provide formatting capabilities
•
The NumberFormat class allows you to format values as
currency or percentages
•
The DecimalFormat class allows you to format values based on
a pattern
•
Both are part of the java.text package
© 2004 Pearson Addison-
3-16
Formatting Output
•
The NumberFormat class has static methods that return a
formatter object
getCurrencyInstance()
getPercentInstance()
•
Each formatter object has a method called format that
returns a string with the specified information in the
appropriate format
© 2004 Pearson Addison-
3-17
See Purchase.java (page 131)
NumberFormat fmt1 =
NumberFormat.getCurrencyInstance();
NumberFormat fmt2 =
NumberFormat.getPercentInstance();
// Print output with appropriate formatting
System.out.println ("Subtotal: " +
fmt1.format(subtotal));
System.out.println ("Tax: " + fmt1.format(tax) +
" at " + fmt2.format(TAX_RATE));
System.out.println ("Total: " +
fmt1.format(totalCost));
Output
Enter the quantity: 3
Enter the unit price: 1.50
Subtotal: $4.50
Tax: $0.27 at 6%
Total: $4.77
© 2004 Pearson Addison-
3-18
Formatting Output
•
The DecimalFormat class can be used to format a floating
point value in various ways
•
For example, you can specify that the number should be
truncated to three decimal places
•
The constructor of the DecimalFormat class takes a string
that represents a pattern for the formatted number
© 2004 Pearson Addison-
3-19
See CircleStats.java (page 134)
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The circle's area: " +
fmt.format(area));
System.out.println ("The circle's circumference: "
+ fmt.format(circumference));
Output
Enter the circle's radius: 7
The circle's area: 153.938
The circle's circumference: 43.982
© 2004 Pearson Addison-
3-20
Outline
Packages
Math Class
Formatting Output
Enumerated Types
© 2004 Pearson Addison-
3-21
Enumerated Types
•
Java allows you to define an enumerated type, which can then
be used to declare variables
•
An enumerated type establishes all possible values for a
variable of that type
•
The values are identifiers of your own choosing
•
The following declaration creates an enumerated type called
Season
enum Season {winter, spring, summer, fall};
•
Any number of values can be listed
© 2004 Pearson Addison-
3-22
Enumerated Types
•
Once a type is defined, a variable of that type can be
declared
Season time;
and it can be assigned a value
time = Season.fall;
•
The values are specified through the name of the type
•
Enumerated types are type-safe – you cannot assign any value
other than those listed
© 2004 Pearson Addison-
3-23
Ordinal Values
•
Internally, each value of an enumerated type is stored as an
integer, called its ordinal value
•
The first value in an enumerated type has an ordinal value
of zero, the second one, and so on
•
However, you cannot assign a numeric value to an enumerated
type, even if it corresponds to a valid ordinal value
© 2004 Pearson Addison-
3-24
Enumerated Types
•
The declaration of an enumerated type is a special type of
class, and each variable of that type is an object
•
The ordinal method returns the ordinal value of the object
•
The name method returns the name of the identifier
corresponding to the object's value
© 2004 Pearson Addison-
3-25