Re: [問題] static runtime問題

看板java作者 (口德是一種美德)時間10年前 (2014/12/20 15:51), 編輯推噓3(3012)
留言15則, 5人參與, 最新討論串2/3 (看更多)
※ 引述《kdok123 (小天)》之銘言: : ex: : class A{ : static void tell(){ : sout("I am A"); : } : } : class B extends A{ : static void tell(){ : super.tell(); //問題 : } : } : 問題: : 有別於c++, Java的static是在runtime執行的 : 這樣我想static的運算應該會少了很多限制 : 所以我測試了一下讓static call super指針(兩個都是runtime才運算的) : 結果發現不行? : 其實static用起來還是跟C++一樣(至少我這麼覺得...) : 請問既然static是在runtime運行的,那為什麼很多runtime的動作沒辦法一起做呢? http://www.quora.com/Why-cant-static-method-access-this-or-super-in-Java 這個人解釋得較好。 Ranjith Kumar S, Computer Engineer A static method which belongs to the class and not to the object(instance). It can access only static data. It can not access non-static data (instance variables). It can be accessed directly by the class name and doesn’t need any object. this keyword can be used to refer current class instance variable. http://www.javatpoint.com/this-k... super is used to refer immediate parent class instance variable. http://www.javatpoint.com/super-... Eventually both this and super keyword refers to instance variables. So a static method cannot refer to “this” or “super” keywords. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.203.156 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1419061919.A.576.html

12/20 17:02, , 1F
嗯! 我知道static不行,只是我想說既然他是runtime執行的
12/20 17:02, 1F

12/20 17:02, , 2F
那應該要可以才對? 有沒有例子可以說明static在java裡
12/20 17:02, 2F

12/20 17:02, , 3F
是runtime執行的呢?
12/20 17:02, 3F

12/20 18:37, , 4F
static{ System.out.println("hello") }
12/20 18:37, 4F

12/20 21:48, , 5F
為什麼在runtime執行要可以? runtime的時候static context
12/20 21:48, 5F

12/20 21:48, , 6F
裡還是沒有instance可以用啊
12/20 21:48, 6F

12/21 12:34, , 7F
我比較好奇的是,既然static member不需要instance,就
12/21 12:34, 7F

12/21 12:36, , 8F
可以呼叫使用,那為啥在撰寫的時候,卻可以使用instance
12/21 12:36, 8F

12/21 12:37, , 9F
來呼叫呢?(有warning,但不影響執行)
12/21 12:37, 9F

12/21 13:53, , 10F
其實不是用instance呼叫,是compiler看reference variable
12/21 13:53, 10F

12/21 13:55, , 11F
的type去選class,這是compile time做的沒用到instance
12/21 13:55, 11F

12/22 14:06, , 12F
你要證明這個很簡單 假設A有個static叫做STATIC()
12/22 14:06, 12F

12/22 14:07, , 13F
A a = null; a.Static(); 你跑跑看就知道了
12/22 14:07, 13F

12/22 14:09, , 14F
你會發現 誒 就算是null一樣可以跑喔 超神奇的(誤
12/22 14:09, 14F

12/22 14:10, , 15F
其實我覺得壓根不該有sugar 不過這太基本教義派了....
12/22 14:10, 15F
文章代碼(AID): #1KbIgVLs (java)
討論串 (同標題文章)
本文引述了以下文章的的內容:
以下文章回應了本文
完整討論串 (本文為第 2 之 3 篇):
文章代碼(AID): #1KbIgVLs (java)