Java 中对象引用与复制

来源:互联网 发布:怎样学python 编辑:程序博客网 时间:2024/06/06 02:59

1. 对象的参数传递和赋值(=)

Java对对象和基本的数据类型的处理是不一样的。当把Java的基本数据类型(如int,char,double等)作为入口参数传给函数体的时候,是"值传递"。

而在Java中用对象的作为入口参数的传递的时候,却不是像C++那样的"引用传递"。能将改变的参数对象状态(即对象的成员变量的值)返回,不能
将一个参数对象赋值给另一个新的参数对象返回。以下是关于方法参数的规则(摘自Core Java 2 Volume I):
・A method cannot modify a parameter of primitive type (that is, numbers or Boolean values).
・A method can change the state of an object parameter.
・A method cannot make an object parameter refer to a new object.

Example:----------------------


Run Result:------------
Testing tripleValue:
Before: percent=10.0
End of method: x=30.0
After: percent=10.0

Testing tripleSalary:
Before: salary=50000.0
End of method: salary=150000.0
After: salary=150000.0

Testing swap:
Before: a=Alice
Before: b=Bob
End of method: x=Bob
End of method: y=Alice
After: a=Alice
After: b=Bob

不过,在任何用"="向对象变量赋值的时候都是"引用传递"。
同样,在Vector、ArraryList、HashTable等Collection、Map里存储的对象也只是对象的引用。

 

2. 对象的复制(clone)

 

对象的复制,不能简单通过“=”赋值,否则也浅拷贝(Shallow Copy), 一般用对象的clone方法进行深拷贝(Deep Copy),这个方法是Object类的protected方法。但是,your code can't simply call anObject.clone(). A subclass can call a protected clone method only to clone its own objects. You must redefine clone to be public to allow objects to be cloned by any method.

 If all data fields in the object are numbers or other basic types, use the default clone method, copying the fields is just fine. But if the object contains references to subobjects like String, Date and so on, you must redefine the clone method to make a deep copy that clones the subobjects as well because of subobjects are mutable.

  ・ Implement the Cloneable interface, and

  ・ Redefine the clone method with the public access modifier.

 The Cloneable interface is one of a handful of tagging interfaces that Java provides. (Some programmers call them marker interfaces.) A tagging interface has no methods; its only purpose is to allow the use of instanceof in a type inquiry:

          if (obj instanceof Cloneable) . . .
Even if the default (shallow copy) implementation of clone is adequate, you still need to implement the Cloneable interface, redefine clone to be public, and call super.clone().

 

Here is an example of a clone method that creates a deep copy:

The clone method of the Object class must explicitly throw a CloneNotSupportedException,or it will cause a compiled error. We usually declared the exception:



 

参考文献:
1. Core Java 2 Volume I 7th Edtion

原创粉丝点击