Packages
Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this section simply as classes and interfaces.
創建
//in the Draggable.java file
package graphics;
public interface Draggable {
. . .
}
//in the Graphic.java file
package graphics;
public abstract class Graphic {
. . .
}
//in the Circle.java file
package graphics;
public class Circle extends Graphic
implements Draggable {
. . .
}
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic
implements Draggable {
. . .
}
//in the Point.java file
package graphics;
public class Point extends Graphic
implements Draggable {
. . .
}
//in the Line.java file
package graphics;
public class Line extends Graphic
implements Draggable {
. . .
}
文件頂部第一行,每個文件只能有1個package
關鍵字。
命名
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage
for a package named mypackage
created by a programmer at example.com
.
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.example.region.mypackage
).
Packages in the Java language itself begin with java.
or javax.
如果按此規則命名出現不合法,使用下劃線:
-
hyphenated-name.example.org,org.example.hyphenated_name
-
example.int,int_.example
-
123name.example.com,com.example._123name
導包
To use a public
package member from outside its package, you must do one of the following:
-
Refer to the member by its fully qualified name
graphics.Rectangle myRect = new graphics.Rectangle();
-
Import the package member
import graphics.Rectangle; Rectangle myRectangle = new Rectangle();
-
Import the member's entire package
import graphics.*; Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();
Java會默認導2個包:
- the
java.lang
package and - the current package (the package for the current file).
Java導父不導子:
Importing java.awt.*
imports all of the types in the java.awt
package, but it does not import java.awt.color
, java.awt.font
, or any other java.awt.xxxx
packages. If you plan to use the classes and other types in java.awt.color
as well as those in java.awt
, you must import both packages with all their files:
import java.awt.*;
import java.awt.color.*;
命名衝突:如果導的包,類名相同,那麼必須加上完整包路徑進行區分
graphics.Rectangle rect;
static import:import the static members
import static java.lang.Math.PI;
參考資料:
Packages https://dev.java/learn/packages/