【发布时间】:2020-11-08 22:09:10
【问题描述】:
我一直在尝试在 Java 中使用多个构造函数。以下是我的代码:
public class MultipleConstructors {
int x = 20;
int y = 50;
String color = "Green";
String color2 = "Yellow";
public MultipleConstructors() {
}
public MultipleConstructors(int numb, int numb2, String colOne, String colTwo) {
x = numb;
y = numb2;
color = colOne;
color2 = colTwo;
}
public MultipleConstructors(int numb3, int numb4, String colThree, String colFour) {
x = numb3;
y = numb4;
color = colThree;
color2 = colFour;
}
public MultipleConstructors(int numb5, int numb6, String colFive, String colSix) {
x = numb5;
y = numb6;
color = colFive;
color2 = colSix;
}
public static void main(String[] args) {
MultipleConstructors myObjOne = new MultipleConstructors(100, 200, "Pink", "Blue");
MultipleConstructors myObjTwo = new MultipleConstructors(300, 500, "Burgandy", "Silver");
MultipleConstructors myObjThree = new MultipleConstructors(800, 1000, "Black", "White");
MultipleConstructors myObjFour = new MultipleConstructors();
System.out.println(myObjOne.x + myObjOne.y + " " + myObjOne.color + " " + myObjTwo.color2 + " " + " : SUCCESS");
System.out.println(myObjTwo.x + myObjTwo.y + " " + myObjTwo.color + " " + myObjTwo.color2 + " " + " : VICTORY");
System.out.println(myObjThree.x + myObjThree.y + " " + myObjThree.color + " " + myObjThree.color2 + " " + " : YES");
System.out.println(myObjFour.x + myObjFour.y + " " + myObjFour.color + " " + myObjFour.color2 + " " + " : YES");
}
}
它在 VS Code 中运行,但不会使用 javac 命令编译。我认为可能是父属性声明后未定义的构造函数public MultipleConstructors() {}。
【问题讨论】:
-
在您的终端中运行以下命令(
javac --version),如果您没有得到版本号输出,则可能是您的机器中没有设置 javac 路径变量 -
输入 javac --version: javac 15.0.1
-
好的,所以当您尝试在 VSCode 中运行代码时,它可以正常工作,而在终端中既不工作也不抛出错误?
-
正确,在 VSCode 中运行但不会编译以便在终端中运行。它抛出由“ClassNotFoundException”引起的错误“找不到或加载主类”
-
我怀疑这是否可以在 VSCode 中编译或以其他方式编译。您有几个具有完全相同参数类型的构造函数,因此编译器在调用它们时无法确定您的意思。
标签: java visual-studio-code constructor javac