为什么有时候'包'是必要的,有时候是不必要的? [英] How come sometimes 'package' is necessary, sometimes is unnecessary?
问题描述
我是Java新手。我按照一些教程使用Eclipse构建了一个简单的Java程序,如下所示:
I am new for Java. I followed some tutorial to build a simple Java program using Eclipse as below:
package samplelib;
public class samplelib {
public static void main (String[] args) {
System.out.println ("sample lib");
}
}
我成功地在Eclipse中运行它。但是当我使用'javac'在命令行编译它然后使用'java'命令运行它时,我得到的消息如错误:无法找到或无法加载主类samplelib。
我删除了第一行package samplelib,再次使用了'javac'/'java'命令。它成功运行。
然后,我回到Eclipse并运行它,我收到以下错误消息:
线程中的异常 mainjava.lang.Error:未解决的编译问题:
at samplelib.samplelib.main(samplelib.java:4)
所以为什么有时我们需要'包装声明',但有时我们不需要?谢谢。
I ran it inside Eclipse successfully. But when I compiled it at command line using 'javac' and then ran it using 'java' command, I got message like "Wrong: can't find or unable to load main class samplelib".
I deleted the first line "package samplelib", used 'javac'/'java' commands again. It rans successfully.
Then, I went back to Eclipse and ran it, I got the following error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at samplelib.samplelib.main(samplelib.java:4)
So, how come sometimes we need 'package statement' but sometimes we don't? Thanks.
推荐答案
包有点像文件夹,其中一组公共文件保存在一起。包中的所有类都保存在一起,如 http://docs.oracle.com/所述javase / tutorial / java / package / index.html [ ^ ]。当您构建具有package
语句的Java程序时,编译的类应该存储在具有相同名称的子目录中。然后调用java
从其父级执行以下命令行:
A package is somewhat like a folder, where a set of common files are kept together. All classes in a package are kept together, as described at http://docs.oracle.com/javase/tutorial/java/package/index.html[^]. When you build a Java program that has apackage
statement, then the compiled class is expected to be stored in a subdirectory with the same name. You then calljava
to execute it from its parent with a command line of the form:
java packagename/classname
您还可以使用 -classpath
选项告诉Java存储类的位置。
You can also use the -classpath
option to tell Java where your classes are stored.
这篇关于为什么有时候'包'是必要的,有时候是不必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!