Search code examples
javaparametersconstructorcannot-find-symbol

Java - pass object as parameter in constructor


My gaol is to use an instance of a class as parameter for another class. I will describe my problem with an example.

public class Color {

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

My goal is to build another constructor that uses instances of my fist class as parameters (for example a car):

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);
}

I get the error "Java cannot find symbol". I tried a lot but can't make it run and I don't fully understand the concepts of classes I guess.


Solution

  • Your constructor name and your class name should be the same. Auto is not the same as car. Just change one of them. Also grey is not defined. I believe you want to use Color.grey which means defining it as 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);
        }
    }