[Java] Object-oriented syntax-Package
What is a package?
- ** Affiliation of class / interface, etc. **
- ** Fully qualified name **: A name that takes into account the namespace
- ** Declared with package instruction **
- Write ** only once ** at the beginning of the file
- All subsequent classes and interfaces belong to that package
- Role of package
- ** Classify types and identify names **
- ** Functional classification **
- java.text Package: Text / Date / Numeric Processing Class:
- java.sql package: SQL related classes
- ** Access control unit **
- Excessive information can be hidden from the outside by defining packages in appropriate units.
Naming rules
- ** Hierarchical structure is represented by
.
**
package com.example.neko.object;
- ** Package name set to lowercase **
- Easy to see class name in uppercase letters
- Each hierarchical element of the package (separated by.) And the simple name of the class / interface ** share the same namespace **
- ** Named based on domain name **
- Add ** Internet domain in reverse order to package prefix **
- Domains are unique so package names don't conflict
- ** Package hierarchy and file system hierarchy are in correspondence **
Default package
- ** Anonymous package **
- If the package declaration is omitted, the subordinate classes belong to the default package.
- I want to avoid it because there is a possibility of name collision
Name resolution
- ** Import command ** can be used to write fully qualified names as simple names
import com.example.neko.object.Animal;
Animal animal = new Animal();
- import imports ** name resolution information **
- It doesn't import the class file itself, so it doesn't make the class file bloated **
- Even if the import destination class is updated ** There is no need to recompile the import source class **
Import type
-
** Single type import **
-
** On-demand import **
-
Import all types under the package
-
Note: Only java.util packages are imported, not packages such as java.util.regex, java.util.stream, etc.
-
java.util and java.util.regex have a flat relationship with each other
-
Benefits of single import
-
** Name resolution has different priorities **
-
Preferred order
-
- The type currently defined in the file
-
- Single import type
-
- Same package type
-
- On-demand import type
-
** Be careful not to duplicate the standard library type name when defining it yourself **
-
Easy to see the relationship between class and package
static import
- ʻImport static fully qualified name`
- You will be able to abbreviate types such as classes, structs, and enumerations as well as packages.
- Simple application with frequently used static methods / constants / static member classes
import static java.lang.Math.abs;
//All static methods under Math class are statically imported
//import static java.lang.Math.*;
public class ImportStatic {
public static void main(String[] args) {
System.out.println(abs(-10));
}
}