Re: [問題] static method

看板java作者時間19年前 (2006/06/19 20:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串7/8 (看更多)
※ 引述《justinC.bbs@ptt.cc (無)》之銘言: : ※ 引述《qrtt1 (隱者)》之銘言: : : 因為你沒有正確產生test物件, 所以不能呼叫test的方法 : : public class test { : : public static void main(String args[]) { : : System.out.print(new test().more(2, 4, 4, 4)); : : } : : public int more(int... num) { : : int total = 0; : : for (int a : num) : : total += a; : : return total; : : } : : } : 還有問題 : 雖然沒產生物件 : 但是在同class 底下 使用function還要加個static : 一直想不出為什麼一樣都是class下的member function還要這樣做呢? : 謝謝~ public class test1 { public static void main(String args[]) { System.out.print(test1.more(2, 4, 4, 4)); } public static int more(int... num) { return ...; } } public class test2 { public void begin() { System.out.print(this.more(2, 4, 4, 4)); } public int more(int... num) { return ...; } } 同一個類別底下 使用static函式呼叫其他static函式時 會以自己的類別(class)作為呼叫的對象 幻想它會自動冠上<<類別名稱>>. 在這個例子中會對應到test1.more(2, 4, 4, 4) 之所以一樣都是類別下的成員函式還得加上static 是因為在非static的成員函式中呼叫其他成員函式時 會以自己的實體(instance)作為呼叫的對象 幻想它會自動冠上this. 在這個例子中會對應到this.more(2, 4, 4, 4) -- 珍惜現在擁有的一切 身外之物不一定能擁有一輩子... -- 〒作者:H45 來自:15-207.dorm.ncu.edu.tw ◎二進位的世界【140.115.50.50‧binary.csie.ncu.edu.tw】
文章代碼(AID): #14bf7_00 (java)
討論串 (同標題文章)
文章代碼(AID): #14bf7_00 (java)