前置知识
Java在处理对象和变量时是不同的.变量传入函数实际上是引用传入函数内,在函数内的变量和函数外传入的变量会使用同一个内存实例中的对象.而基本类型则是会拷贝一份相同的值,相当于方法体内的局部变量.
代码实现
public class Variables {
private int value =4;
private String str ="init String";
private void initMember(){
this.value =456;
this.str = "qwer";
}
public static void main(String[] args) {
Variables variables = new Variables();
variables.initMember();
System.out.println(variables.value+"---"+variables.str);
}
}
```
输出结果
```
456---qwer
```
####Cloneable接口的实现
1 clone分为影子clone和深clone,影子克隆比如在对象中包含了一个变量时,那么这个对象的clone只复制了包含的变量引用.
2 clone的实现需要继承Cloneable接口,然后重写clone()方法.
#####代码实现
```
//实现影子clone
public class CloneA implements Cloneable {
private int anInt;
public Object clone(){
CloneA cloneA =null;
try {
cloneA = (CloneA)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return cloneA;
}
}
```
```
//实现深clone
public class DeepClone implements Cloneable {
private String value;
private CloneA cloneA;
public Object clone() {
DeepClone deepClone = null;
try {
deepClone = (DeepClone) super.clone();
//该成员变量实现了Cloneable接口,进行clone
deepClone.cloneA = (CloneA) cloneA.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return deepClone;
}
}
```