The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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:
Client.java
add:package mygame.client;
Server.java
add:package mygame.server;
:Utilities.java
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
.
mygame/client/
place:Client.java
mygame/server/
place:Server.java
mygame/shared/
place:Utilities.java
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. Client.java
and Server.java
need to import the Utilities
class, which they can do in one of two ways:
import mygame.shared.*; --or-- import mygame.shared.Utilities;
Also, Server.java
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: mygame.zip
You might need to change your proposed import code to reflect our implementation.