Chapter 9. Packages

 <  Day Day Up  >  

Over the preceding few chapters, we've worked primarily with one or two classes (and interfaces) at a time. But in larger applications, creating dozens of different classes and grouping them logically together, perhaps with multiple interfaces, is common. To group classes and interfaces together, we use packages . You may wonder why we'd want to group classes and interfaces. To learn why, let's consider a hypothetical scenario.

Imagine you're creating a game with a background music player. You create the game in-house, but you use a third-party component for the music player. In the game, you have a class for the player, named Player . Unbeknownst to you, the music player component also defines a class named Player ! When you attempt to use the music player component, it doesn't work because its version of the Player class is ignored (your game's Player class is defined first, and once a class is defined, it cannot be redefined). This conflict is called a namespace collision or naming conflict .

What to do?

Well, you could rename your Player class to something like GamePlayer , but that would require a lot of changes to your existing code. Besides, you like the name Player and don't really want to change it. And even if you did change your class's name to GamePlayer , you have no guarantee that some other component you need won't conflict with it. Or conversely, if you are distributing your classes, you have no way of anticipating the class names in use by other developers who might use your code.

Fortunately, packages solve your problem. A package is a unique place to put a group of classes, much as a directory on your hard drive is a unique place to put a group of files. And just as multiple files named index.html can exist in more than one folder without conflicts, a class named Player can exist in more than one package without conflicts. Packages allow multiple classes of the same name to coexist without namespace collisions, because each package constitutes a namespace within which the class name is unique. A namespace is a set of names that contains no duplicates. The Domain Name System (DNS) defines a namespace in which registrants can reserve a domain name, such as moock .org , without fear that someone else might use the same name.

 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net