看板 java 關於我們 聯絡資訊
※ 引述《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
kdok123: 嗯! 我知道static不行,只是我想說既然他是runtime執行的 12/20 17:02
kdok123: 那應該要可以才對? 有沒有例子可以說明static在java裡 12/20 17:02
kdok123: 是runtime執行的呢? 12/20 17:02
luoqr: static{ System.out.println("hello") } 12/20 18:37
ssccg: 為什麼在runtime執行要可以? runtime的時候static context 12/20 21:48
ssccg: 裡還是沒有instance可以用啊 12/20 21:48
icydream: 我比較好奇的是,既然static member不需要instance,就 12/21 12:34
icydream: 可以呼叫使用,那為啥在撰寫的時候,卻可以使用instance 12/21 12:36
icydream: 來呼叫呢?(有warning,但不影響執行) 12/21 12:37
ssccg: 其實不是用instance呼叫,是compiler看reference variable 12/21 13:53
ssccg: 的type去選class,這是compile time做的沒用到instance 12/21 13:55
Killercat: 你要證明這個很簡單 假設A有個static叫做STATIC() 12/22 14:06
Killercat: A a = null; a.Static(); 你跑跑看就知道了 12/22 14:07
Killercat: 你會發現 誒 就算是null一樣可以跑喔 超神奇的(誤 12/22 14:09
Killercat: 其實我覺得壓根不該有sugar 不過這太基本教義派了.... 12/22 14:10