錯誤代碼
if (choice.equals("蘋果")) {
Mobile mobile = new IphoneMobile(material1);
}
if (choice.equals("三星")) {
Mobile mobile = new SamMobile(material1);
}
return mobile; // 編譯錯誤:mobile 不在作用域內
修正
Mobile mobile = null; // 方法開頭宣告
if (choice.equals("蘋果")) {
mobile = new IphoneMobile(material1);
} else if (choice.equals("三星")) {
mobile = new SamMobile(material1);
} else if (choice.equals("小米")) {
mobile = new MiMobile(material1);
}
return mobile;
原則
- 區域變數在 **{ }** 區塊內有效,離開區塊即銷毀。
- 跨
if-else 分支使用時,必須在**共同祖先區塊**(通常是方法開頭)宣告。