[問題] static與non static

看板java作者 (鴻)時間11年前 (2014/07/04 21:15), 11年前編輯推噓2(206)
留言8則, 2人參與, 最新討論串1/2 (看更多)
有沒有大神可以解釋 System.out.println() 為什麼一個static的參用 可以 呼叫 non-static的方法 public final class System{ public final static printStream out = null; } public class printStream{ public void println() } public static void main(String[] args){ System.out.println(); } 可以過關 但我自寫 public final class A{ public static B b = new B(); }} public class B { public static void m(){ System.out.print(1223456); } public void m1(){ System.out.print(1223456); } public static void main(String[] args) { A.b.m1(); } } 卻無法過關 感恩 我一直以為 static 不能直接對未實例化 的non-static作使用 -- 作宅男其實也沒什麼不好。 你千萬別問我為什麼, 因為你不是,就算解釋了,你依舊不會了解。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.115.236.15 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1404479753.A.747.html

07/04 21:41, , 1F
static 的只是 out, out 本身參照到了一個物件, println 是
07/04 21:41, 1F

07/04 21:41, , 2F
對那個物件作用的
07/04 21:41, 2F
我看java附的原始碼 System.java public final static printStream out = null; 看不出這裡有參照到物件阿 老師還特地拿這個System.out.println() 出來說 static 呼叫了non-static方法

07/04 21:44, , 3F
至於你的例子應該是你多貼了一層 A 的關係
07/04 21:44, 3F
我打一打,後來改用複製貼上的時候沒檢查多貼了一層A ※ 編輯: e002311 (114.45.146.247), 07/05/2014 02:57:25 ※ 編輯: e002311 (114.45.146.247), 07/05/2014 02:58:26

07/05 05:00, , 4F
用參照呼叫non-static方法是哪邊有問題?
07/05 05:00, 4F

07/05 05:05, , 5F
是在static context中直接呼叫同一class的non-static member
07/05 05:05, 5F

07/05 05:10, , 6F
(隱含用this呼叫目前物件的member)才不行
07/05 05:10, 6F

07/05 05:11, , 7F
重點在目前物件(this)不能用,不是non-static不能用
07/05 05:11, 7F

07/05 05:16, , 8F
不用特地以System.out解釋,想想A.b.toString()能不能用?
07/05 05:16, 8F
文章代碼(AID): #1Jjga9T7 (java)
討論串 (同標題文章)
文章代碼(AID): #1Jjga9T7 (java)