Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from www.BruceEckel.com.
- Add Rhomboid to Shapes.java. Create a Rhomboid, upcast
it to a Shape, then downcast it back to a Rhomboid. Try
downcasting to a Circle and see what happens.
- Modify Exercise 1 so that it uses instanceof to check the type
before performing the downcast.
- Modify Shapes.java so that it can “highlight” (set a
flag) in all shapes of a particular type. The toString( ) method for
each derived Shape should indicate whether that Shape is
- Modify SweetShop.java so that each type of object creation is
controlled by a command-line argument. That is, if your command line is
“java SweetShop Candy,” then only the Candy object is
created. Notice how you can control which Class objects are loaded via
the command-line argument.
- Add a new type of Pet to PetCount3.java. Verify that it is
created and counted correctly in main( ).
- Write a method that takes an object and recursively prints all the classes
in that object’s hierarchy.
- Modify Exercise 6 so that it uses Class. getDeclaredFields( )
to also display information about the fields in a class.
- In ToyTest.java, comment out Toy’s default constructor
and explain what happens.
- Incorporate a new kind of interface into ToyTest.java and
verify that it is detected and displayed properly.
- Write a program to determine whether an array of char is a primitive
type or a true object.
- Implement clearSpitValve( ) as described in the summary.
Implement the rotate(Shape) method described in this chapter, such
that it checks to see if it is rotating a Circle (and, if so,
doesn’t perform the operation).
- In ToyTest.java, use reflection to create a Toy object using
the nondefault constructor.
- Look up the interface for java.lang.Class in the JDK documentation
from java.sun.com. Write a program that takes the name of a class as a
command-line argument, then uses the Class methods to dump all the
information available for that class. Test your program with a standard library
class and a class you create.
- Modify the regular expression in ShowMethods.java to additionally
strip off the keywords native and final (hint: use the
“or” operator ‘|’).