|
 |
|
| |
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.
- Write a program that creates an ArrayList object without explicitly
importing java.util.*.
- In the section labeled package: the library unit, turn the
code fragments concerning mypackage into a compiling and running set of
Java files.
- In the section labeled Collisions, take the code fragments
and turn them into a program and verify that collisions do in fact occur.
Generalize the class P defined in this chapter by adding all the
overloaded versions of rint( ) and rintln( ) necessary
to handle all the different basic Java types.
- Create a class with public, private, protected, and
package-access fields and method members. Create an object of this class and see
what kind of compiler messages you get when you try to access all the class
members. Be aware that classes in the same directory are part of the
default package.
- Create a class with protected data. Create a second class in the
same file with a method that manipulates the protected data in the first
class.
- Change the class Cookie as specified in the section labeled
protected: inheritance access. Verify that bite( ) is
not public.
- In the section titled Class access youll find code
fragments describing mylib and Widget. Create this library, then
create a Widget in a class that is not part of the mylib package.
- Create a new directory and edit your CLASSPATH to include that new
directory. Copy the P.class file (produced by compiling
com.bruceeckel.tools.P.java) to your new directory and then change
the names of the file, the P class inside, and the method names. (You
might also want to add additional output to watch how it works.) Create another
program in a different directory that uses your new class.
- Following the form of the example Lunch.java, create a class called
ConnectionManager that manages a fixed array of Connection
objects. The client programmer must not be able to explicitly create
Connection objects, but can only get them via a static method in
ConnectionManager. When the ConnectionManager runs out of objects,
it returns a null reference. Test the classes in main( ).
- Create the following file in the c05/local directory (presumably in your
CLASSPATH):
// c05:local:PackagedClass.java
package c05.local;
class PackagedClass {
public PackagedClass() {
System.out.println("Creating a packaged class");
}
}
Then create the following file in a directory other than c05:
// c05:foreign:Foreign.java
package c05.foreign;
import c05.local.*;
public class Foreign {
public static void main (String[] args) {
PackagedClass pc = new PackagedClass();
}
}
Explain why the compiler generates an error. Would making the Foreign class part of the c05.local package change anything?
|
|
|