前置知識(shí)
Java在處理對(duì)象和變量時(shí)是不同的.變量傳入函數(shù)實(shí)際上是引用傳入函數(shù)內(nèi),在函數(shù)內(nèi)的變量和函數(shù)外傳入的變量會(huì)使用同一個(gè)內(nèi)存實(shí)例中的對(duì)象.而基本類(lèi)型則是會(huì)拷貝一份相同的值,相當(dāng)于方法體內(nèi)的局部變量.
代碼實(shí)現(xiàn)
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);
}
}
```
輸出結(jié)果
```
456---qwer
```
####Cloneable接口的實(shí)現(xiàn)
1 clone分為影子clone和深clone,影子克隆比如在對(duì)象中包含了一個(gè)變量時(shí),那么這個(gè)對(duì)象的clone只復(fù)制了包含的變量引用.
2 clone的實(shí)現(xiàn)需要繼承Cloneable接口,然后重寫(xiě)clone()方法.
#####代碼實(shí)現(xiàn)
```
//實(shí)現(xiàn)影子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;
}
}
```
```
//實(shí)現(xiàn)深clone
public class DeepClone implements Cloneable {
private String value;
private CloneA cloneA;
public Object clone() {
DeepClone deepClone = null;
try {
deepClone = (DeepClone) super.clone();
//該成員變量實(shí)現(xiàn)了Cloneable接口,進(jìn)行clone
deepClone.cloneA = (CloneA) cloneA.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return deepClone;
}
}
```