Start of Tutorial > Start of Trail > Start of Lesson | Search |
To create a package, you simply put a class or interface in it. To do this, you put apackage
statement at the top of the source file in which the class or interface is defined. For example, the following code appears in the source fileCircle.java
and puts the Circle class in thegraphics
package:Thepackage graphics; public class Circle extends Graphic implements Draggable { . . . }Circle
class is a public member of thegraphics
package.You must include a
package
statement at the top of every source file that defines a class or interface that is to be a member of thegraphics
package. So you would also include the statement inRectangle.java
and so on:The scope of the package statement is the entire source file, so all classes and interfaces defined inpackage graphics; public class Rectangle extends Graphic implements Draggable { . . . }Circle.java
andRectangle.java
are also members of thegraphics
package. If you put multiple classes in a single source file, only one may be declared public and it must share the name of the source file's basename. Only public package members are accessible from outside the package.
Note: Some compilers might allow more than one public file per.java
file. However, we recommend that you use the one-public-class-per-file convention, since it makes public classes easier to find and works for all compilers.If you do not use a
package
statement, 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 Java classes and interfaces, it is conceivable and even likely that two programmers will use the same name for two different classes. In fact, the previous example does just that: It defines aRectangle
class when there is already aRectangle
class in thejava.awt
package. Yet, the compiler allows both classes to have the same name. Why? Because they are in different packages and the actual name of each class includes the package name. That is, the name of theRectangle
class in thegraphics
package is reallygraphics.Rectangle
, and the name of theRectangle
class in thejava.awt
package is reallyjava.awt.Rectangle
.This works just fine unless two independent programmers use the same name for their packages. What prevents this? Convention.
By Convention: Companies use their reversed Internet domain name in their package names, like this:com.company.package
. Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or project name after the company name, for example,com.company.region.package
.
Start of Tutorial > Start of Trail > Start of Lesson | Search |