Exercises
Exercise 2-1. Write a
Circle
class that is similar to theRect
class. Define amove( )
method and anisInside( )
method. (Recall that a circle is defined as all points within a given radius from the center. Test for insideness by using the Pythagorean theorem to compute the distance between a point and the center of the circle.) Also, define aboundingBox( )
method that returns the smallestRect
that encloses the completeCircle
. Write a simple program to test the methods you’ve implemented.Exercise 2-2. Write a class that represents a person’s mailing address. It should have separate fields for the name, street address, city, state, and ZIP code. Define a
toString( )
method that produces nicely formatted output.Exercise 2-3. Modify the
ComplexNumber
class of Example 2-5 to override theequals( )
andhashCode( )
methods inherited fromObject
. Use theIntList
class of Example 2-7 as a model.Exercise 2-4. Modify Example 2-5 again to implement
Comparable
as Example 2-7 does. Note that this is not as straightforward as its seems, since there is not an unambiguous ordering for complex numbers. One possible way to order complex numbers is by their magnitude. Although this ordering is suitable for some applications, note that it is not compatible with theequals( )
method. That is, acompareTo( )
method based on magnitude will return (equality) for numbers that are nonequal according to theequals( )
method.Exercise 2-5 . Modify the
IntList
class of Example 2-7 to create a
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.