0

So, my code is pretty simple. Just wanted to try and create a package.

// /home/user1/Code/packageTest/src/myPackage/Test.java

package myPackage;

public class Test
{

    public static void main(String[] args)
    {
        System.out.println("Hello, world.");
    }
}

let's say this code is in some directory myPackage.

If I comment out the first line (package specification) the code runs fine, prints the message. It compiles either way, but if it compiled with the package line not commented out, it causes a run-time error.

What do I need to do to successfully make a package? I can't seem to find the right search terms to turn up a real explanation on this, only stuff about package naming conventions, why they're used to separate namespaces, bla bla bla. The next part of this experiment was going to be trying import my own packages, obviously I didn't even get that far.

Something to do with the classpath perhaps...? What and where is my "base directory"? Any information on this would be greatly appreciated.

4

1 回答 1

3

您应该在名称为的目录中的 java 文件中创建该类myPackage。然后你应该走出那个目录并编译它如下

javac myPackage/Test.java

然后使用完全限定类名 (FQCN) 运行它,如下所示:

java myPackage.Test

例如

C:\Temp\test1>type myPackage\Test.java
package myPackage;

public class Test
{

    public static void main(String[] args)
    {
        System.out.println("Hello, world.");
    }
}
C:\Temp\test1>javac myPackage/Test.java

C:\Temp\test1>java myPackage.Test
Hello, world.

C:\Temp\test1>
于 2012-09-25T02:04:32.687 回答