Summer vacation wasted a month, but it is worth, after all, learned to swim! Well, anyway, since the files in Java are organized by class, the concept of package is often used, as illustrated below.
Java is an object-oriented language, and programs are in the smallest unit of class, and all programs must be placed in the class definition. The suffix of the Java source file must be . Java, usually the main file name of the Java program source files can be arbitrary, but if the Java program source code defines a public class, the main file name must be the same as the class, the general class name of the first letter is used to capitalize. The usual habit is to define only one class per source file, with different classes using different source file definitions. For different classes, we use packages to organize. The specific examples are as follows:
//File Tiger.java
PackageAnimal;classtiger{ Public voideat () {System.out.println ("Tiger Eat Meat"); }}//file Goat.java PackageAnimal;classgoat{ Public voideat () {System.out.println ("Goats eat Grass"); }}//file Dog.java PackageAnimal;classdog{ Public voideat () {System.out.println ("Dogs eat meat and Grass"); }}
File Animal_eat.java
Package animal;
public class Animal_eat
{
Public Dog dog = new Dog ();
Public Goat Goat = new Goat ();
Public Tiger Tiger = new Tiger ();
public void Summary ()
{
Dog.eat ();
Goat.eat ();
Tiger.eat ();
}
}
We put Tiger, Dog, Goat, animal_eat four classes under the package Animal. Note that Tiger, Dog, Goat these three classes are default access rights and therefore can be accessed by other classes under the same package, but not by other classes outside the package.
-D. Dog.java Goat.java Tiger.java Animal_eat.java
You will find a Animal subfolder in the folder with four compiled files Dog.class, Goat.class, Tiger.class, Animal_eat.class. Again we return to the current folder and define a test class,
File name Biology.java
Import animal. Animal_eat; Public class biology{ publicstaticvoid main (string[] args) { New animal_eat (); A.summary (); } }
This class is located outside the animal package and imports the Animal_eat class through import. Also compile and run the program:
Javac-D. The results of the Biology.javajava Biology program run as follows: Dogs eat meat and grassgoats eat grasstiger eat meat
The above is a simple use of Java package example, through the program in the good organization of the class, making our program code more logical.
Use of package in Java