作者e002311 (鴻)
看板java
標題[問題] static與non static
時間Fri Jul 4 21:15:50 2014
有沒有大神可以解釋
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
推 LPH66:static 的只是 out, out 本身參照到了一個物件, println 是 07/04 21:41
→ LPH66:對那個物件作用的 07/04 21:41
我看java附的原始碼 System.java
public final static printStream out = null;
看不出這裡有參照到物件阿
老師還特地拿這個System.out.println()
出來說
static 呼叫了non-static方法
推 LPH66:至於你的例子應該是你多貼了一層 A 的關係 07/04 21:44
我打一打,後來改用複製貼上的時候沒檢查多貼了一層A
※ 編輯: e002311 (114.45.146.247), 07/05/2014 02:57:25
※ 編輯: e002311 (114.45.146.247), 07/05/2014 02:58:26
→ ssccg:用參照呼叫non-static方法是哪邊有問題? 07/05 05:00
→ ssccg:是在static context中直接呼叫同一class的non-static member 07/05 05:05
→ ssccg:(隱含用this呼叫目前物件的member)才不行 07/05 05:10
→ ssccg:重點在目前物件(this)不能用,不是non-static不能用 07/05 05:11
→ ssccg:不用特地以System.out解釋,想想A.b.toString()能不能用? 07/05 05:16