|
|
|
|
Exercises
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.
- Demonstrate a second level of aliasing. Create a method that takes a
reference to an object but doesn’t modify that reference’s object.
However, the method calls a second method, passing it the reference, and this
second method does modify the object.
- Create a class MyString containing a String object that you
initialize in the constructor using the constructor’s argument. Add a
toString( ) method and a method concatenate( ) that
appends a String object to your internal string. Implement
clone( ) in MyString. Create two static methods that
each take a MyString x reference as an argument and call
x.concatenate("test"), but in the second method call clone( )
first. Test the two methods and show the different effects.
- Create a class called Battery containing an int that is a
battery number (as a unique identifier). Make it cloneable and give it a
toString( ) method. Now create a class called Toy that
contains an array of Battery and a toString( ) that prints
out all the batteries. Write a clone( ) for Toy that
automatically clones all of its Battery objects. Test this by cloning
Toy and printing the result.
- Change CheckCloneable.java so that all of the clone( )
methods catch the CloneNotSupportedException rather than passing it to
the caller.
- Using the mutable-companion-class technique, make an immutable class
containing an int, a double, and an array of char.
Modify Compete.java to add more member objects to classes
Thing2 and Thing4 and see if you can determine how the timings
vary with complexity—whether it’s a simple linear relationship or if
it seems more complicated.
- Starting with Snake.java, create a deep-copy version of the snake.
- Implement the Collection interface in a class called
CloningCollection by using a private ArrayList to provide
the container functionality. Override the clone( ) method so that
CloningCollection performs a “conditional deep copy”; it
attempts to clone( ) all the elements it contains, but if it cannot
it leaves the reference(s) aliased.
href="TIJ319_002.htm">[116] In C, which generally handles small bits of data, the default is pass by value. C++ had to follow this form, but with objects pass by value isn’t usually the most efficient way. In addition, coding classes to support pass by value in C++ is a big headache.
public class Cloneit implements Cloneable {
public static void main (String[] args)
throws CloneNotSupportedException {
Cloneit a = new Cloneit();
Cloneit b = (Cloneit)a.clone();
}
}
|
|
|