2017-11-25 174 views
0
String model; 
int year; 
enum Color {GREEN, BLUE, RED}; 
double price;  

顏色色調;將ENUM類型指定給構造函數

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

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

可以這樣做嗎?當我用主要方法實際製作對象時仍然出現錯誤。

+0

不,你沒有。這不知道枚舉的工作。你已經聲明瞭一個類型,你沒有定義一個實例。 – Ivan

+0

嘿,那我該怎麼做? –

回答

1

此語法:this.Color = shade; 引用Car類中名爲Color的實例字段。 但您在Car類中沒有任何Color字段。

此:

enum Color {GREEN, BLUE, RED}; 

是枚舉類的聲明。

Car剛剛引進的字段可以分配給它一個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; 
    } 
} 
+0

哦,明白了!問題修復非常感謝:) –

+0

@DannyBorisOv如果這個答案解決了你的問題,你可以考慮接受它來獎勵回答者,讓未來的訪問者知道正確的答案是什麼。 –

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