1

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.

Paul Ahuevo
  • 131
  • 1
  • 1
  • 13
  • You could use `Car myCar = new Car(80, new Color("grey"));` and then read more tutorials. – Kayaman Mar 22 '17 at 20:01
  • 1
    `public Color grey = new Color("grey");` will cause a `StackOverflowError`, because it's a member variable inside the `Color` class: to create a `Color`, you create a `Color`, which creates a `Color`, which creates a `Color`.... – Andy Turner Mar 22 '17 at 20:02
  • You have multiple issues here, and you should always post *the entire error message*--in this case, it shows you exactly where the unknown symbol is. – chrylis -cautiouslyoptimistic- Mar 22 '17 at 20:05

2 Answers2

3

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);
    }
}
Peyman Mahdian
  • 512
  • 4
  • 15
0

A cannot find symbol error usually means that it's a problem with scope--that is, what bits are visible where. In your case, grey is defined on the class Color, but you're trying to use it from Car. If you are trying to build a set of reusable Color objects, make grey static final (the static means that it belongs to the entire class Color and not to a specific color), and call it GREY to fit conventions.

Then, from your main method, you still won't see GREY because it's inside another scope. You can tell Java where to find it by calling it Color.GREY.

chrylis -cautiouslyoptimistic-
  • 67,584
  • 19
  • 106
  • 140