Danny Boris Ov
Danny Boris Ov

Reputation: 69

Assign ENUM type to constructor

String model;
int year;
enum Color {GREEN, BLUE, RED}; 
double price;     

Color shade;

public Car(String model, int year, Color shade, double price) {

    this.model = model;
    this.year = year; 
    this.shade= shade;
    this.price = price;
}

Is this ok? still gives error when i acctually make the object with the main method.

Upvotes: 1

Views: 198

Answers (2)

eddie
eddie

Reputation: 1250

enum Color {GREEN, BLUE, RED} ;

public class Car{

    String m_model;
    int m_year;
    Color m_color;
    double m_price;

    public Car(String model, int year, Color shade, double price) {

        this.m_model = model;
        this.m_year = year; 
        this.m_color = shade;
        this.m_price = price;

        System.out.println("A new Car has been created!");
    }


    static public void main(String[] args)
    {

        Car car = new Car("Ferrari", 2017, Color.RED, 350000);
    }
}

Upvotes: 0

davidxxx
davidxxx

Reputation: 131316

This syntax : this.Color = shade; refers an instance field named Color in the Car class. But you don't have any Color field in the Car class.

This :

enum Color {GREEN, BLUE, RED};

is the enum class declaration.

Just introduce a field in Car to be able to assign to it a Color :

public class Car {
    String model;
    int year;
    Color color;
...
    public Car(String model, int year, Color shade, double price) {
      this.model = model;
      this.year = year;
      this.color = shade;
      this.price = price;
    }
}

Upvotes: 1

Related Questions