当我使用javac编译几个 .java 文件时,出现了一些“重复类” 错误,但是我在代码中找不到错误。
有四个 .java 文件,所有这些文件都位于Windows的同一文件夹中。
import dx.*;
import dx.shapes.*;
class MyApp {
public static void main(String[] args) {
System.out.println("This is a test application.");
Rectangle rect = new Rectangle(10, 20);
rect.Speak();
Circle circle = new Circle(15);
circle.Speak();
Worker worker = new Worker();
worker.Speak();
}
}
package dx.shapes;
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void Speak(){
System.out.println("I'm a rectangle, width:" + this.width + ", height:" + this.height);
}
}
package dx.shapes;
public class Circle {
private int x, y;
private int radius;
public Circle() {
this(0, 0, 10);
}
public Circle(int radius) {
this(0, 0, radius);
}
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public void Speak(){
System.out.println("I'm a circle, radius:" + this.radius);
}
}
package dx;
public class Worker {
public void Speak(){
System.out.println("I'm a worker.");
}
}
在Windows命令行中,我使用 javac 来编译这些源代码:
javac MyApp.java Rectangle.java Circle.java Worker.java
但是我唯一得到的是错误列表:
Rectangle.java:3: error: duplicate class: dx.shapes.Rectangle
public class Rectangle {
^
MyApp.java:8: error: cannot access Rectangle
Rectangle rect = new Rectangle(10, 20);
^
bad source file: .\Rectangle.java
file does not contain class Rectangle
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Circle.java:3: error: duplicate class: dx.shapes.Circle
public class Circle {
^
MyApp.java:11: error: cannot access Circle
Circle circle = new Circle(15);
^
bad source file: .\Circle.java
file does not contain class Circle
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Worker.java:3: error: duplicate class: dx.Worker
public class Worker {
^
MyApp.java:14: error: cannot access Worker
Worker worker = new Worker();
^
bad source file: .\Worker.java
file does not contain class Worker
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
6 errors
我不知道怎么了。为什么?
答案 0 :(得分:2)
请参考编译器的文档:Arrangement of Source Code
主要:
将类和接口组织到一个程序包中时,该程序包表示为目录,而所有子程序包均表示为子目录。
假设您的根源目录为src
,则文件的排列方式应为
src/
|
+ - MyApp.java
|
+ = dx/
|
+ - Worker.java
|
+ = shapes/
|
+ - Circle.java
+ - Rectangle.java
要编译对src
目录的更改并使用:
/src> javac *.java dx/*.java dx/shapes/*java
或者,对于Windows:
C:\src>javac *.java dx\*.java dx\shapes\*java
由于在MyApp
中引用了所有类,因此您只需编译该文件,编译器就会查找并编译其他类:
src> javac MyApp.java
此后,最好一次编译所有文件(相同的文档):
在命令行或自变量文件中指定的源文件的顺序并不重要。 javac会将文件作为一个整体编译在一起,并将自动解析各个源文件中声明之间的任何依赖关系。
答案 1 :(得分:0)
完全编译目录中的所有文件
javac目录名/ *。java
答案 2 :(得分:0)
您只能调用主类,即MyApp
只是使主类javac MyApp.java
然后是java MyApp