/** * Test 2: Methods can change the state of object parameters */ System.out.println("\nTesting tripleSalary:"); Employee harry = new Employee("Harry", 50000); System.out.println("Before: "+harry.hashCode()+" salary=" + harry.getSalary()); tripleSalary(harry); System.out.println("After: salary=" + harry.getSalary());
/** * Test 3: Methods can't attach new objects to object parameters */ System.out.println("\nTesting swap:"); Employee a = new Employee("Alice", 70000); Employee b = new Employee("Bob", 60000); System.out.println("Before: "+a.hashCode()+" a=" + a.getName()); System.out.println("Before: "+b.hashCode()+" b=" + b.getName()); swap(a, b); System.out.println("After: "+a.hashCode()+" a=" + a.getName()); System.out.println("After: "+b.hashCode()+" b=" + b.getName()); }
privatestaticvoidswap(Employee x, Employee y){ Employee temp = x; x = y; y = temp; System.out.println("End of method: "+x.hashCode()+" x=" + x.getName()); System.out.println("End of method: "+y.hashCode()+" y=" + y.getName()); }
privatestaticvoidtripleValue(double x){ x = 3 * x; System.out.println("End of Method X= " + x); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Testing tripleValue:基本数据类型,在栈开辟独立的存储单元,2个栈对象操作独立的存储单元,相互不影响;在tripleValue方法中,percent栈对象值赋值给x栈对象。 Before: percent=10.0 x End = 30.0 After: percent=10.0
Testing tripleSalary:栈引用对象harry和x都是指向同一个堆地址。在tripleSalary方法中,栈对象x对堆中实体对象的修改,直接影响harry引用对象指向堆对象的值。 harry Before hashCode: 581409841 salary=50000 x End hashCode: 581409841 salary=10000000 harry After hashCode: 581409841 salary=10000000
Testing swap:栈对象a、b指向2个不同的堆对象空间,在swap方法内,新建2个栈对象x、y指向栈对象a、b所指的堆对象。那么a,x和b,y都是指向同一个堆对象,那么x,y栈对象的值进行交换,并不会影响a和b,只是x,y所指的堆对象地址变化。如果,x和y对堆对象进行操作,必然会影响到a和b获取的值。 Before: 704603837 a=Alice Before: 1051858901 b=Bob x End hashCode: 1051858901 x=Bob y End hashCode: 704603837 y=Alice After: 704603837 a=Alice After: 1051858901 b=Bob
例子3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package valueParam;
publicclassDemo4{ staticvoidswap(StringBuffer a2, StringBuffer b2){ a2.append(" more"); System.out.println("--------a-----------" + a2); // One more System.out.println("--------b-----------" + b2); // Two b2 = a2; System.out.println("--------b-----------" + b2); // One more }
publicstaticvoidmain(String args[]){ StringBuffer a1 = new StringBuffer("One"); StringBuffer b1 = new StringBuffer("Two"); swap(a1, b1); System.out.println("a is " + a1 + "\nb is " + b1); } }
1 2 3 4 5
--------a-----------One more --------b-----------Two --------b-----------One more a is One more b is Two