User Guide

Packages and namespaces 41
Importing packages
If you want to use a class that is inside a package, you must import either the package or the
specific class. This differs from ActionScript 2.0, where importing classes was optional.
For example, consider the SampleCode class example from earlier in this chapter. If the class
resides in a package named samples, you must use one of the following import statements
before using the SampleCode class:
import samples.*;
or
import samples.SampleCode;
In general, import statements should be as specific as possible. If you plan to use only the
SampleCode class from the samples
package, you should import only the SampleCode class
rather than the entire package to which it belongs. Importing entire packages may lead to
unexpected name conflicts.
You must also place the source code that defines the package or class within your classpath.
The classpath is a user-defined list of local directory paths that determines where the compiler
will search for imported packages and classes. The classpath is sometimes called the build path
or source path.
After you have properly imported the class or package, you can use either the fully qualified
name of the class (samples.SampleCode) or merely the class name by itself (SampleCode).
Fully qualified names are useful when identically named classes, methods, or properties result
in ambiguous code, but can be difficult to manage if used for all identifiers. For example, the
use of the fully qualified name results in verbose code when you instantiate a SampleCode
class instance:
var mySample:samples.SampleCode = new samples.SampleCode();
As the levels of nested packages increase, the readability of your code decreases. In situations
where you are confident that ambiguous identifiers will not be a problem, you can make your
code easier to read by using simple identifiers. For example, instantiating a new instance of the
SampleCode class is much less verbose if you use only the class identifier:
var mySample:SampleCode = new SampleCode();
If you attempt to use identifier names without first importing the appropriate package or
class, the compiler will not be able to find the class definitions. On the other hand, if you do
import a package or class, any attempt to define a name that conflicts with an imported name
will generate an error.