A mechanism for organizing classes. There are many classes in the Java language. Therefore, if a large number of classes are organized by purpose and function, it will be easier to use for each purpose and class management will be easier.
Declare with "package package name;". (Correct) Describe in the first line of the source code
Hello.java
package jp.co.xxx;
import aaa.*;
public class Hello(){
System.out.println("hello world!");
}
(Error) import is described before the package declaration
Hello.java
import aaa.*;
package jp.co.xxx;
public class Hello(){
System.out.println("hello world!");
}
Must be written on the first line of the source code Only comments can be written before the package declaration
If the package is different, even a class with the same class name will be a different class. If there are classes with the same name, the compiler and JVM cannot determine which class to use, which may result in a compilation error or the intended class not being used. In that case, use it to avoid duplicate names. The compiler and JVM judge the class by "package name.class name". Therefore, it is desirable that the package name is as unique as possible. By the way, the expression in "package name.class name" is called a fully qualified class name, and the abbreviation for "class name" is called a simple name.
Fully qualified class name: "java.lang.String" Simple name: "String"
By dividing the class into multiple packages, access control can be performed on a package-by-package basis. By dividing the class in the package into a public class and a non-public class, it is possible to prevent the class different from the expected class from being used. ** Access modifier type ** "Private": Only accessible from within the same class "Protected": Classes in the same package or different packages can be accessed from within a subclass that inherits that class. "Public": accessible from all classes None: accessible from all classes in the same package
Hello.java
package jp.co.xxx;
public class Hello(){
System.out.println("hello world!");
}
Declaration of Bye class belonging to jp.co.xxx package
Bye.java
package jp.co.xxx;
class Bye(){
System.out.println("Bye!");
}
The public Hello class can be used by classes belonging to other packages, but the non-public Bye class cannot be used.
The package has a directory structure. The directories under the source directory are packages. If it is a "jp.co.xxx.Hello" class, it will be like "\ jp \ co \ xxx \ Hello.class". Classes always belong to some package, and classes that omit the package declaration are interpreted as belonging to an anonymous package by default. There is no class that does not belong to the package.
Recommended Posts