Namespace Accessibility

Like variable and method definitions, namespace definitions can be modified by the access-control modifiers public, internal, protected, and private. Taken in combination, the location of a namespace definition and the access-control modifier of that definition determine where the resulting namespace identifier can be used.

Here are some general rules to help you decide where to define your namespaces:

  • When you need a namespace throughout a program or across a group of classes, define it at the package level.

  • When you need a namespace to define the visibility of variables and methods within a single class only, define it at the class level.

  • When you need a namespace only temporarily within a function, and you know the URI of the namespace, but you cannot access that namespace directly, define it at the function level.

Let's look at some examples, starting with namespaces defined at the package level.

Accessibility of Package-Level Namespace Definitions

In the following code, we define a namespace identifier, fruit, in the package kidsgame:

package kidsgame {
  public namespace fruit = "";

Because fruit is declared at the package level with the access-control modifier public, it can be used to qualify any variable or method in the program. Of course, code outside the kidsgame package would have to import the namespace fruit before using it, as in:

package anyPackage { // Import the fruit namespace import kidsgame.fruit; public ...

Get Essential ActionScript 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.