CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Packages

Packages
Packages
Introduction

A Package:

  • Is a named collection of classes and interfaces
  • Easily imports related classes into new programs
  • Encourages other programmers to reuse software
  • Helps avoid naming conflicts or collisions

Give every package a unique name. A class's package name tells the compiler how to locate the class. For example, if a class instantiates a Scanner object, the Java compiler must be directed to the package that contains the Scanner class, that is, to java.util.

When creating classes for others to use:

  • Protect your work
    • Do not provide users with source code in files with .java extensions
    • Provide users with compiled files with .class extensions
  • Include package statement at beginning of class file
    • Place compiled code into indicated folder

A class that will be placed in a package for others to use must be public. If a class is not public, it can be used only by other classes within the same package.

If you do not specify a package for a class, it is placed in an unnamed default package.

You cannot import more than one package in one statement; for example, if multiple packages are stored in a folder named com, you cannot import them with the statement import com.*. The import statement only imports files from one folder at a time.

The package statement, import statements, and comments are the only statements that appear outside class definitions in Java program files.

Previous | Introduction | Store classes | Compile classes | Make classes | Next