静态类(static)与java值传递、引用传递小测

时间:2025-03-16 13:34:37

java中都是值传递。直接上代码了:

 class TestStaticA {

     static {
System.out.println("b");
} public TestStaticA() {
System.out.println("TestStaticA construction method");
} protected void say() {
System.out.println("TestStaticA say hello ");
} static {
System.out.println("bb");
} }

继承类:

 public class TestStatic extends TestStaticA {

     public static int i = 1;
static {
System.out.println("i" + i);
i=2;
} public TestStatic() {
System.out.println("TestStatic construction method"+i);
} public void say() {
System.out.println("TestStatic say hello");
} public void appendex(StringBuffer a, StringBuffer b) {
a.append("a");
b=a;
} public static void main(String[] args) {
TestStaticA test = new TestStatic();
new TestStatic();
test.say();
StringBuffer a = new StringBuffer("a");
StringBuffer b = new StringBuffer("b");
new TestStatic().appendex(a,b);
System.out.println(a.toString()+":"+b.toString());
} }

结果:

 b
bb
i1
TestStaticA construction method
TestStatic construction method2
TestStaticA construction method
TestStatic construction method2
TestStatic say hello
TestStaticA construction method
TestStatic construction method2
aa:b

注意红色答案部分,虽然是一个值传递(引用副本),但是引用副本所指向的内容发生改变,当方法结束时,引用副本消亡,但是已经改变了原来的内容。

相关文章