前置知識
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;
}
}
```