靜態類(static)與java值傳遞、引用傳遞小測

java中都是值傳遞。直接上代碼了:java

 1 class TestStaticA {
 2 
 3     static {
 4         System.out.println("b");
 5     }
 6 
 7     public TestStaticA() {
 8         System.out.println("TestStaticA construction method");
 9     }
10 
11     protected void say() {
12         System.out.println("TestStaticA say hello ");
13     }
14 
15     static {
16         System.out.println("bb");
17     }
18 
19 }

繼承類:app

 1 public class TestStatic extends TestStaticA {
 2 
 3     public static int i = 1;
 4     static {
 5         System.out.println("i" + i);
 6         i=2;
 7     }
 8 
 9     public TestStatic() {
10         System.out.println("TestStatic construction method"+i);
11     }
12 
13     public void say() {
14         System.out.println("TestStatic say hello");
15     }
16     
17 
18     
19     public void appendex(StringBuffer a, StringBuffer b) {
20         a.append("a");
21         b=a;
22     }
23 
24     public static void main(String[] args) {
25         TestStaticA test = new TestStatic();
26         new TestStatic();
27         test.say();
28         StringBuffer a = new StringBuffer("a");
29         StringBuffer b = new StringBuffer("b");
30         new TestStatic().appendex(a,b);
31         System.out.println(a.toString()+":"+b.toString());
32     }
33 
34 }

結果:spa

 1 b
 2 bb
 3 i1
 4 TestStaticA construction method
 5 TestStatic construction method2
 6 TestStaticA construction method
 7 TestStatic construction method2
 8 TestStatic say hello
 9 TestStaticA construction method
10 TestStatic construction method2
11 aa:b

注意紅色答案部分,雖然是一個值傳遞(引用副本),可是引用副本所指向的內容發生改變,當方法結束時,引用副本消亡,可是已經改變了原來的內容。code

相關文章
相關標籤/搜索