package: the library unit
Code organization
If you use a package statement, it must appear as the first non-comment in the file.
Creating unique package names
import 从别的包中引入类时,所对应类和方法须为public
Collisions
A custom tool library
Using imports to change behavior
Package caveat
Java access specifiers
Package access
public: interface access
The default package
private: you can’t touch that!
protected: inheritance access
If you create a new package and inherit from a class in another package, the only members you have access to are the
public members of the original package. (
Of course, if you
perform the inheritance in the same package, you can manipulate all the members that have
package access.)
protected also gives package access—that is, other classes in the same package may access
protected elements.
protected同时拥有package access和继承访问的访问模式。
Interface and implementation
Class access
In Java, the access specifiers can also be used to determine which classes within a library will be available to the users of that library. If you want a class to be available to a client programmer, you use the public keyword on the entire class definition. This controls whether the client programmer can even create an object of the class. (需要其构造方法也为public)
However, there’s an extra set of constraints:
1. There can be only one public class per compilation unit (file). The idea is that each compilation unit has a single public interface represented by that public class. It can have as many supporting package-access classes as you want. If you have more than one public class inside a compilation unit, the compiler will give you an error message.
2. The name of the public class must exactly match the name of the file containing the compilation unit, including capitalization.
3. It is possible, though not typical, to have a compilation unit with no public class at all. In this case, you can name the file whatever you like (although naming it arbitrarily will be confusing to people reading and maintaining the code).
1. There can be only one public class per compilation unit (file). The idea is that each compilation unit has a single public interface represented by that public class. It can have as many supporting package-access classes as you want. If you have more than one public class inside a compilation unit, the compiler will give you an error message.
2. The name of the public class must exactly match the name of the file containing the compilation unit, including capitalization.
3. It is possible, though not typical, to have a compilation unit with no public class at all. In this case, you can name the file whatever you like (although naming it arbitrarily will be confusing to people reading and maintaining the code).