|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
To create a package, you put a class or an interface in it. To do this, you put apackagestatement at the top of the source file in which the class or the interface is defined. For example, the following code appears in the source fileCircle.javaand puts theCircleclass in thegraphicspackage:Thepackage graphics; public class Circle extends Graphic implements Draggable { . . . }Circleclass is a public member of thegraphicspackage.You must include a
packagestatement at the top of every source file that defines a class or an interface that is to be a member of thegraphicspackage. So you would also include the statement inRectangle.javaand so on:The scope of thepackage graphics; public class Rectangle extends Graphic implements Draggable { . . . }packagestatement is the entire source file, so all classes and interfaces defined inCircle.javaandRectangle.javaare also members of thegraphicspackage. If you put multiple classes in a single source file, only one may be public, and it must share the name of the source files base name. Only public package members are accessible from outside the package.If you do not use a
packagestatement, your class or interface ends up in the default package, which is a package that has no name. Generally speaking, the default package is only for small or temporary applications or when you are just beginning development. Otherwise, classes and interfaces belong in named packages.
With programmers all over the world writing classes and interfaces using the Java programming language, it is likely that two programmers will use the same name for two different classes. In fact, the previous example does just that: It defines aRectangleclass when there is already aRectangleclass in thejava.awtpackage. Yet the compiler allows both classes to have the same name. Why? Because they are in different packages, and the fully qualified name of each class includes the package name. That is, the fully qualified name of theRectangleclass in thegraphicspackage isgraphics.Rectangle, and the fully qualified name of theRectangleclass in thejava.awtpackage isjava.awt.Rectangle.This generally works just fine unless two independent programmers use the same name for their packages. What prevents this problem? Convention.
By Convention: Companies use their reversed Internet domain name in their package names, like this:com.company.package. Some companies now choose to drop the first elementcom.in this example from their package names. Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name, for example,com.company.region.package.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.