1. What is the package?
Java language pack is a very effective class management mechanism. When the two source files contain the same name of the class, how can we distinguish this class, which requires a package, the package name is valid purpose of distinguishing the same name of the class, a different source file name when two classes the same, they can be distinguished from each other by different membership packages. So I think that the main role of the package is to achieve the classification of the class.
2. How to use package it
Now I use IDEA Demo:
First, write the names of two different classes of the same content:
public class People{
void f(){
System.out.println("我是bao1的people");
}
}
public class People{
void f(){
System.out.println("我是bao2的people");
}
}
我们知道这两个类不能放在同一个包中(否则编译器会报错)
Below we create two packages, the names were bao1, bao2 and these two classes were placed in two packages:
Compiler not being given.
So the question here again, how do we use them?
Here there have been an import statement, this statement can make a package of classes can be used in another package in the category, how does it work? Let's continue:
we create a master class in bao1 in, in this class we want these two names the same code type of operation is as follows:
package bao1;
import bao2.People;
public class animal {
public static void main(String[] args) {
bao2.People speak = new People();
speak.f();
bao1.People speaks = new bao1.People();
speaks.f();
}
}
The results are as follows:
For the use of import are:
import package path to reference class;.
If you want to refer to all classes in a package, you can use * to represent, * on behalf of all.
Above learning summary includes personal, such as the existence unreasonable, welcome to point out, learn from each other.