Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
Java How to Program, 6/e

ISBN:
0-13-148398-6
© 2005
pages: 1576
Buy the Book!
Amazon logo
InformIT logo

The Java class libraries are divided into packages of related classes and interfaces. Most Java programs you build reuse existing packages, such as the Java class libraries, third party libraries or libraries developed within your organization. This tutorial shows how create your own packages of classes for reuse or distribution. The tutorial is intended for students or professionals who are alreadyfamiliar with building Java classes.

Download the code for this tutorial here.

[Note: This tutorial is an excerpt (Section 8.16) of Chapter 8, Class and Objects: A Deeper Look, from our textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.390-396. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

8.16 Time Class Case Study: Creating Packages

We have seen in almost every example in the text that classes from preexisting libraries, such as the Java API, can be imported into a Java program. Each class in the Java API belongs to a package that contains a group of related classes. As applications become more complex, packages help programmers manage the complexity of application components. Packages also facilitate software reuse by enabling programs to import classes from other packages (as we have done in most examples). Another benefit of packages is that they provide a convention for unique class names, which helps prevent class-name conflicts (discussed later in this section). This section introduces how to create your own packages.

Steps for Declaring a Reusable Class

Before a class can be imported into multiple applications, it must be placed in a package to make it reusable. Figure 8.18 shows how to specify the package in which a class should be placed. Figure 8.19 shows how to import our packaged class so that it can be used in an application. The steps for creating a reusable class are:

1. Declare a public class. If the class is not public, it can be used only by other classes in the same package.

2. Choose a package name and add a package declaration to the source-code file for the reusable class declaration. There can be only one package declaration in each Java source-code file, and it must precede all other declarations and statements in the file. Note that comments are not statements, so comments can be placed before a package statement in a file.

3. Compile the class so that it is placed in the appropriate package directory structure.

4. Import the reusable class into a program and use the class.

Page 1 | 2 | 3 | 4 | 5
Return to Tutorial Index