Re: [問題] 建構子問題

看板java作者 (好多目標)時間13年前 (2012/03/15 00:04), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/7 (看更多)
※ 引述《cyberwizard (Gavin)》之銘言: : public class test { : static int c; : : public static void main(String[] args) { : int a = 1; : int b = 2; : //new test(a, b); : System.out.printf("兩數字相加 %d, %d 答案為 %d %n ", a, b, c); : } : : public test(int a, int b){ : c =a + b; : } : } : : 去掉不必要得部份,這樣執行會得到 : 兩數字相加 1, 2 答案為 0 : : 把註解去掉,會得到 : 兩數字相加 1, 2 答案為 3 : : 雖然物件建構子當作方法用很怪,但是功能還是正常的 : : -- : ※ 發信站: 批踢踢實業坊(ptt.cc) : ◆ From: 140.123.85.140 : 推 jodoken:建構值當方法用很奇怪嗎? 03/14 18:34 : 推 LaPass:非常奇怪.... 03/14 19:28 : 推 mars90226:建構子就是在你需要那個物件時才呼叫阿~ 03/14 22:15 正常的用法 public class Coffee { int c; // this is non-static public static void main(String[] args) { int a = 1; int b = 2; Coffee coffee = new Coffee(a, b); // 新的物件要接 System.out.println("(a,b,c)", a, b, coffee.c); } public Coffee(int a, int b) { c = a + b; } } Constructor (中文是建構子?) 的確是一個不必宣告 return type 的 method ,但這不表示它沒有回傳東西。以上面的例子來說,constructor 回傳的東西就 是 Coffee。如果需要一個沒有回傳的 method,那就用 void 來宣告,像上面的 main() 就是了。 原 po 的例子裡另一個不好的 pattern,是在 constructor 裡面改 static variable。Static variable 是所有同 class 的 object 共用的,不應該在新 建一個 object 時更改。假設上面的 c 表示咖啡有沒有加奶精好了,如果你讓 它是 static 的話,表示你自己點一杯咖啡加奶精時,會讓餐廳裡所有其他人的 咖啡一起加奶精,這聽起來就很怪 XD -- If I don't know I don't know, I think I know If I don't know I know, I think I don't know ── R. D. Laing -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 207.171.191.60
文章代碼(AID): #1FOC6AzA (java)
討論串 (同標題文章)
文章代碼(AID): #1FOC6AzA (java)