Java官方笔记11包

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个包

  1. the java.lang package and
  2. 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.colorjava.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/

你可能感兴趣的:(java,笔记,开发语言)