靜態類(static)與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 }

繼承類:

 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 }

結果:

 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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM