Re: [問題] static method

看板java作者 (隱者)時間19年前 (2006/06/19 17:44), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/8 (看更多)
※ 引述《hpeter (hpeter)》之銘言: : ※ 引述《justinC (無)》之銘言: : : public class test { : : public static void main(String args[]) { : : System.out.print(more(2,4,4,4)); : : } : : public static int more(int... num) : : { : : int total=0; : : for(int a:num) : : total+=a; : : return total; : : } : : } : : 為什麼在class test底下 : : more method一定要加static 才能給過? : : 而其他class則不需用呢? : 小弟覺得 因為被 static function 用到的東西 : 一定要有static 之修飾 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method more(int[]) from the type test at test.main(test.java:3) ============================================================================= 俺在初學java時也是和您一樣的想法,因為這樣的錯誤訊息。我在被用到的method field 都加了static,後來發現原來只要產生了instance就能正確地呼叫。 所以,我們有權選擇static or non-static,至於如何選擇簡單的判斷是 1. 以field而言 你要所有instance共同一個變數時, 那就static。 2. 以method而言 有static時會想想, 這功能到底屬不屬於該class, 如果不屬於乾脆丟到雜項的class 如果屬於那只好免強放一下唄>"< -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 163.26.34.105
文章代碼(AID): #14bd7xzL (java)
討論串 (同標題文章)
文章代碼(AID): #14bd7xzL (java)