編譯器在;{
期望之後在new Stock[2];
處顯示錯誤。簡單的Java「新」概念問題
public class TestStockUI {
Stock[] stock = new Stock[2];
stock[0] = new Stock("Microsoft", "MSFT", 15.69);
stock[1] = new Stock("Google", "GOGL", 323.98);
public TestStockUI() { }
}
然後我改變了它,就像下面導致相同的錯誤。
public class TestStockUI {
Stock[] stock = new Stock[2];
stock[0] = new Stock("Microsoft", "MSFT", 15.69);
stock[1] = new Stock("Google", "GOGL", 323.98);
}
這解決了這個問題,但我不知道爲什麼。
public class TestStockUI {
Stock[] stock = new Stock[2];
{
stock[0]=new Stock("Microsoft","MSFT",15.69);
stock[1]=new Stock("Google","GOGL",323.98);
}
}
(+1)或者,他可以將它們移動到構造函數 – 2011-04-05 18:05:16
或者,將stock [0]和stock [1]的初始化移動到構造函數中。 – justkt 2011-04-05 18:05:30
@Brian,@Justkt - 是的,這是大多數Java開發人員可能期望的。 – 2011-04-05 18:07:42