JScript .NET, Part III: Classes and Namespaces: Packaging A Namespace - Doc JavaScript | WebReference

JScript .NET, Part III: Classes and Namespaces: Packaging A Namespace - Doc JavaScript


JScript .NET, Part III: Classes and Namespaces

Packaging a Namespace

You create a namespace with the package statement. It combines one or more classes into a logical group called a namespace. Let's look at an example:


// Create a simple package containing a class with
// a single field (President).
package USA {
   class Head {
      static var President : String = "Bush";
   }
};
// Create another simple package containing two classes.
// The class Head has the field PrimeMinister.
// The class Localization has the field Currency.
package UK {
   public class Head {
      static var PrimeMinister : String = "Blair";
   }
   public class Localization {
      static var Currency : String = "Pound";
   }
};
// Use another package for more specific information.
package USA.Florida {
   public class Head {
      static var Governor : String = "Bush";
   }
};
// Declare a local class that shadows the imported classes.
   class Head {
      static var Governor : String = "Davis";
   }
// Import the USA, UK, and USA.Florida packages.
import USA;
import UK;
import USA.Florida;
// Access the package members with fully qualified names.
print(Head.Governor);
print(USA.Head.President);
print(UK.Head.PrimeMinister);
print(USA.Florida.Head.Governor);
// The Localization class is not shadowed locally,
// so it can be accessed with or without a fully qualified name.
print(Localization.Currency);
print(UK.Localization.Currency);

Here is the output of the above code:

Davis
Bush
Blair
Bush
Pound
Pound

Notice that when the class location is ambiguous, you must use fully-qualified names. The class Head, for example, appears in USA, UK, USA.Florida, and locally, so the namespace must prefix this class. The class Localization, however, appears only in the UK namespace, so there is no need to use the fully-qualified variable names.


Next: How to load assemblies


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: May 6, 2002
Revised: May 6, 2002

URL: https://www.webreference.com/js/column109/4.html