Java packages
From wikinotes
java's package/module system is different from both python/cpp. Modules are assigned to packages using a statement in code, which does not necessarily have anything to do with the organization of your code within your filesystem.
Defining Packages
In this example, despite HelloWorld 1/2 residing in the same directory, one is assigned to the package
beginner.examples
and the other is assigned toexpert.examples
.src/ HelloWorld_1.java HelloWorld_2.javapackage beginner.examples class HelloWorld_1 { static void main(String[] args){ System.out.println("Hello World"); } }package expert.examples class HelloWorld_2 { static void main(String[] args){ System.out.println("Hello World"); } }
Imports
imports work by importing the objects from a class directly into the current namespace.
import beginner.examples.HelloWorld_1 // imports all classes defined within 'HelloWorld_1.java' import beginner.examples.* // imports all classes defined within modules in the package 'beginner.examples'
Static Imports
Static imports allow you to access static methods like functions directly, without any reference to their objects. Java docs caution to use this sparingly.
// MyClass.java class MyClass { static void print_hi() { System.out.println("hi") }; }// App.java import static MyClass; class App { public static void main() { print_hi(); // <-- not MyClass.print_hi() } }