The Java™ Tutorials
Trail: Learning the Java Language
Lesson: Packages
Home Page > Learning the Java Language > Packages

Answers to Questions and Exercises: Creating and Using Packages


Question 1: Assume that you have written some classes. Belatedly, you decide that they should be split into three packages, as listed in the table below. Furthermore, assume that the classes are currently in the default package (they have no package statements).

Package Name Class Name
mygame.server Server
mygame.shared Utilities
mygame.client Client

a. What line of code will you need to add to each source file to put each class in the right package?
Answer 1a: The first line of each file must specify the package:

In add:
package mygame.client;
In add:
package mygame.server;:
In add:
package mygame.shared;

b. To adhere to the directory structure, you will need to create some subdirectories in your development directory, and put source files in the correct subdirectories. What subdirectories must you create? Which subdirectory does each source file go in?
Answer 1b: Within the mygame directory, you need to create three subdirectories: client, server, and shared.

In mygame/client/ place:
In mygame/server/ place:
In mygame/shared/ place:

c. Do you think you'll need to make any other changes to the source files to make them compile correctly? If so, what?
Answer 1c: Yes, you need to add import statements. and need to import the Utilities class, which they can do in one of two ways:

import mygame.shared.*;
import mygame.shared.Utilities;

Also, needs to import the Client class:

import mygame.client.Client;


Exercise 1: Download three source files:

a. Implement the changes you proposed in question 1, using the source files you just downloaded.
b. Compile the revised source files. (Hint: If you're invoking the compiler from the command line (as opposed to using a builder), invoke the compiler from the directory that contains the mygame directory you just created.) Answer 1: Download this zip file with the solution:
You might need to change your proposed import code to reflect our implementation.

Previous page: Questions and Exercises: Creating and Using Packages