Re: [問題] static method

看板java作者 (BadKido)時間18年前 (2006/06/19 18:07), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/8 (看更多)
※ 引述《justinC (無)》之銘言: : ※ 引述《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還要這樣做呢? : 謝謝~ ==站內文件== 嗯 先想清楚static的用意 static是用來產生一個"class專屬"的"共用"資料成員或方法 並不屬於個別的"object" 也就是說static成員 是屬於此class(類別)所專有 且不是object 所以也就沒有this參考 又因為宣告static的方法 沒有this參考 所以在static方法中 不能使用non-static成員 因為沒有this參考(等於沒有參考的位址) 他無法抓出你想要抓出的static裡的成員 另外main之所以用static是因為初始化時 利用static來 首先產生一個實體 然後才由main來初始化其他的物件 開始整個程式 你可以參考良葛格學習筆記 裡面提到很多基本的概念 相信很有幫助 下面是有關static的部分 http://caterpillar.onlyfun.net/Gossip/JavaGossip-V1/AboutStaticMember.htm 若有錯誤 煩請糾正 謝謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.117.169.23
文章代碼(AID): #14bdTeYV (java)
討論串 (同標題文章)
文章代碼(AID): #14bdTeYV (java)