Exercises

  • Exercise 2-1. Write a Circle class that is similar to the Rect class. Define a move( ) method and an isInside( ) 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 a boundingBox( ) method that returns the smallest Rect that encloses the complete Circle. 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 the equals( ) and hashCode( ) methods inherited from Object. Use the IntList 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 the equals( ) method. That is, a compareTo( ) method based on magnitude will return (equality) for numbers that are nonequal according to the equals( ) 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.