问题描述
如何编译并运行以下程序:
How do I compile and run the following programs:
Test1.java:
Test1.java:
package A;
public class Test1
{
public int a = 1;
}
Test2.java:
Test2.java:
package B;
import A.*;
public class Test2
{
public static void main(String [] args)
{
Test1 obj = new Test1();
System.out.println(obj.a);
}
}
我是新手包。
如果我使用 javac * .java
进行编译并手动创建dir A,请将Test1.class复制到其中并手动创建dir B并复制Test2。进入它然后运行 java B.Test2
它可以工作。我确信这不是正确的做法。请建议。
I'm new to packages.If I compile using javac *.java
and manually create dir A, copy Test1.class into it and manually create dir B and copy Test2.class into it and then run java B.Test2
it works. I'm sure this is not the right way of doing it. Please suggest.
推荐答案
您需要将java文件保存在正确的目录结构中:
You need to keep your java files in the correct directory structure:
A/Test1.java
B/Test2.java
通常只需在主类上调用 javac
即可,因为所有依赖项都将自动处理。在我说 javac B / Test2.java
后,它看起来像这样:
It's usually sufficient to only invoke javac
on your main class, as all dependencies will be handled automatically. After I say javac B/Test2.java
, it looks like this:
A/Test1.class
A/Test1.java
B/Test2.class
B/Test2.java
我可以用 java B.Test2
运行程序。
如果仅仅在主类上运行 javac
是不够的,那么你可能需要一个构建系统。
If it's not enough just to run javac
on your main class, you'll probably need a build system.
这篇关于编译并运行这个java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!