When programming in Java, if you create a lot of classes to be created, it will be difficult to manage unless you organize them properly. Also, if you have created a class jointly, you need to distinguish it from the class you created when you use a class created by another person. Describes the package for doing that.
In Java, you can collect classes to create a collection of classes called a package. If you think of a class as a part, you can say that a collection of strongly related parts is a ** package **. For example, when creating a program that performs scientific calculations, it is not necessary to describe complicated calculation formulas from scratch in the program, and scientific calculations can be easily performed by obtaining a scientific calculation package and using it. I will. Each package has a unique name to distinguish it from other packages. Java recommends that you put the reverse order of your Internet domain at the beginning of your package to ensure that your unique naming is followed. For example, if the domain name is "blogramming.co.jp", the package name will start with "jp.co.blogramming".
Java is designed to work on the packages you need, when you need them, and as much as you need them. Therefore, it is necessary to specify which package to import by using import in the program. One way to do this is to use a package with a specified package name. The program shown below uses the DecimalFormat class of the java.text package. By adding "." After the package name and specifying the class name, an instance of the DecimalFormat class included in the java.text package is created.
PackageTest1.java
class PackageTest1{
public static void main(String[] args){
int x=1234567;
java.text.DecimalFormat df=new java.text.DecimalFormat(",###");
System.out.println("x="+x);
System.out.println("x="+df.format(x));
}
}
By writing the package name, it is possible to use the classes included in the package, but the program description has become very long. Use import here. By using import, the package can be imported, so it is possible to use it as a class at hand with only the class name without describing the package name. However, import does not physically copy the class in the package or insert it in the program list, but logically imports it, so once you import it, you do not have to do it later. Instead, you should always write import while writing the program.
PackageTest2.java
import java.text.DecimalFormat;
class PackageTest2{
public static void main(String[] args){
int x=1234567;
DecimalFormat df=new DecimalFormat(",###");
System.out.println("x="+x);
System.out.println("x="+df.format(x));
}
}
Recommended Posts