1 of 15

Package Declaration

The package declaration at the top of the source file declares that the Elevator Frame class belongs to the package named elevator.

When the package declaration is absent from a file, all the classes contained in the file belong to unnamed package.

A class in a named package can be referred in two ways.

2 of 15

Using Packages

    • Class in a named package can be referred to in two different ways
      • Using the fully qualified name packagename.ClassName
      • We can refer to the ElevatorPanel class in package elevator as

elevator.ElevatorPlanel

3 of 15

Benefits

4 of 15

Figure

5 of 15

6 of 15

Importing a class in the package

  • Importing the class using the simple class name

    • We can import a class or all the classes in the designated package using

Import packagename.ClassName;

Import packagename.*;

    • The ElevatorPanel class in package elevator can simply be referred to as elevator when either of the following import clauses occurs at the top of source file

Import elevator.ElevatorPanel;

Import elevator.*;

7 of 15

Accessing Class in a package

8 of 15

Creating your Package

9 of 15

10 of 15

11 of 15

12 of 15

Packages Directory Paths

  • The CLASSPATH

    • List of directories and/or jar files. The compiler will look in these directories for any precompiled files it needs.

    • The CLASSPATH can be set as an environmental variable or specified on the command line using –classpath option.

    • The CLASSPATH is also used by the Java Virtual Machine to load classes.

13 of 15

14 of 15

Compile Package Classes

  • Compile the program
    • To compile the program, we must change the working directory to the source directory root, and issue the following command

c:\project> javac -d . elevator\*.java

    • By compiling everything, we get the recent version of all the classes.
    • Specify –d . option to tell the compiler to put the classes in a package structure starting at the root.

15 of 15

��������Notes on the import statement�

  • Import ONLY imports public classes from the specified package
    • Classes which are not public cannot be referenced from outside their package.

  • There is no way to "import all classes except one"
    • import either imports a single class or all classes within the package
    • Note: importing has no runtime or performance implications. It is only importing a namespace so that the compiler can resolve class names.

  • Import statements must appear at the top of the file after the package statement and before any class or interface definitions.