package
declaration which
precedes all non-comment code. The package name
must be the same as the enclosing directory.
For example, here are two files in the packagetest
directory.
package packagetest; class ClassA { public static void main(String[] args) { ClassB.greet(); } }and
package packagetest; class ClassB { static void greet() { System.out.println("Hi"); } }Note that these source files must be named
ClassA.java
and ClassB.java
(case matters)
and they must be in a directory named packagetest
.
packagetest
directory.
To compile the classes:
javac packagetest/ClassB.java javac packagetest/ClassA.javaTo run the
main
program in ClassA
.
java packagetest.ClassAor
java packagetest/ClassA
In windows the "/" can be replaced by the "\" in the javac
command, but not in the java
command.
Generally use a forward slash ("/") because it is used
more commonly than the backslash in other places as well.