【发布时间】:2020-09-17 22:26:56
【问题描述】:
我想编译一个包含两个类的 java 源文件。我怎样才能做到这一点?我编译我的代码:
javac -classpath Class_ex_1.java
public class Class_ex_1 {
public static void main(String[] args) {
int del = 7;
int del_1 = 2;
int rem = del % del_1;
System.out.println("First value :" + del + "\n");
System.out.println("Second value :" + del_1 + "\n"); //
System.out.println("Display meaning a % b :" + rem + "\n"); //
Hello_test n1 = new Hello_test();
System.out.println("Display parameter from class:" + n1.getColor + "\n");
}
}
public class Hello_test {
String color = "Red";
public String getColor(){
return color;
}
}
【问题讨论】:
-
JLS 只允许每个文件有一个公共类,并且该类必须与文件同名 (
FileName.java->public Class FileName { ... })。因此,提供的代码不是有效的 java 代码,因此无法编译。 -
第 1 步:从与文件命名不同的类中删除
public。 --- 第 2 步:从命令中删除-classpath。 -
我这样做了,我得到了错误:javac Class_ex_1.java Class_ex_1.java:13: 错误:找不到符号 System.out.println("显示类中的参数:" + n1.getColor + " \n"); ^ 符号:变量 getColor 位置:Hello_test 类型的变量 n1 1 错误
-
您错误地调用了该方法。将
n1.getColor更改为n1.getColor() -
这能回答你的问题吗? Can a java file have more than one class?
标签: java java-console