Java - 在构造函数中将对象作为参数传递

标签 java parameters constructor cannot-find-symbol

<分区>

我的 jail 是使用一个类的实例作为另一个类的参数。我将用一个例子来描述我的问题。

public class Color {

    public String color;
    public Color (String color) {
        this.color = color;
    }
    public Color grey = new Color("grey");
}

我的目标是构建另一个使用我的第一个类的实例作为参数的构造函数(例如汽车):

public class car {

    int PS;
    Color color;

    public Auto (int PS, Color color) {
        this.PS = PS;
        this.color = color;
    }

    public static void main (String args[]) {
        car myCar = new car(80, grey);
}

我收到错误“Java 找不到符号”。我尝试了很多但无法让它运行,而且我没有完全理解我猜的类的概念。

最佳答案

您的构造函数名称和您的类名称应该相同。 Autocar 不同。只需更改其中一个即可。 grey 也没有定义。我相信您想使用 Color.grey,这意味着将其定义为 static

public class Color {

    public String color;
    public Color (String color) {
        this.color = color;
    }
    public static Color grey = new Color("grey");
}

public class car {

    int PS;
    Color color;

    public car (int PS, Color color) {
        this.PS = PS;
        this.color = color;
    }

    public static void main (String args[]) {
        car myCar = new car(80, Color.grey);
    }
}

关于Java - 在构造函数中将对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42961556/

相关文章:

java - 将文件分配给图像编译错误: javax. imageio.IIOException

java - 如何修复以下错误 : "Error: Main method not found in class"

c++ - 宏中使用的模板参数有问题

regex - 将正则表达式传递给 perl 子程序

c++ - 构造函数错误 : error: expected ‘,’ or ‘...’ before numeric constant

c++ - 从子类设置 const 成员值

java - 从命令行运行 jar 文件时设置目录路径

java - 如何使用JavaParser遍历一些Java源代码的AST(抽象语法树)的所有节点?

java - 如何使用 if 语句在构造函数中声明最终字符串?

java - 因果一致性与顺序一致性有何不同?