Intermediate Programming Instructor: Greg Shaw

foreheadsobstinacyDéveloppement de logiciels

15 août 2012 (il y a 9 années et 1 mois)

388 vue(s)

Computer Programming I






Instructor: Greg Shaw

COP 2210
















Packages


I.


About Packages




A package is a folder for storing
related

classes




For example, the JOptionPane class lives in the
javax.swing

package and classes

such as PrintWriter, File, and IOException
reside in the package
java.io




We may also
create
our

own packages
to
store
our
classes




C
lasses in packages
are easily reused
, via the
import

statement




For each class that goes in a particular package, use the

package

statement with the name of the package (folder)




package

name

;




T
he
package

statement must be the first statement in the
file (i.e., it must appear before the imp
orts and the
class declaration). Only
comments

may appear before the
package

stat
ement




To specify a
path

in a package statement, periods are used
instead of slashes.
If you do not specify a path, the package
folder must
be in the same folder as
the

source code
. In
NetBeans, this is the
src

folder of the project




The package
java.lang
, which contains the most commonly used
classes such as String, Math, System, and the “wrapper” classes,
is the only package that does not require an
import

statement



II.

Using Packages

in Netbeans


1.

Create the package folder in your
src

folder


2.

S
tore your cl
ass definitions (i.e.,
.java

files)
in the desired
package/folder
and
compile
each one


3.

Make sure each class in the package begins with the appropriate
package statement


4.

Write a client program that
import
s classes from your package
and store it in the
src

folder (
not

in the package folder
)


5.

C
ompile
and run
your client
program. If you make any changes to
the classes in the package, don’t forget to re
-
compile them


6.

Once the classes in your package folder have been compiled, you
may remove the .
java

files
.
That way, other programmers may use
your classes
but

not have access to the code.


III.


Netbeans

Will Do It
All
Automatically!


1.

Right click on the project icon in the
Projects

pane at the
left, and choose
New

and then
Java

Package
...


2.

Enter a name for the pack
age

(the default location will be the
src folder of the project) and click
Finish


3.

Select
the classes from the default package

(i.e., the
src

folder), right c
lick and
choose
Refactor

and then
Move
...





Do NOT select your “test” class

-

l
eave it in the src

folder


4.

S
elect the package that you
just created
from the
To
P
ackage

list and click
Refactor




NetBeans will automatically insert the proper
package

statement in each class



NetBeans will
also automatically
insert the proper
import

statement
(s)

in
your test

class



import

package
-
name.class
-
name

;