標籤:blog file person lan put java .com 參數 dex
一、建立對象的四種方法:
a. new語句;
b. 利用反射,調用描述類的Class對象的newInstance()執行個體方法;
c. 調用對象的clone();
d. 還原序列化;
其中new 和 newInstance()會調用類的構造方法,而clone()和還原序列化不會;
Cloneable介面:
Cloneable介面裡沒有定義方法,僅用於標記對象,clone()方法是Object類裡面的方法,是一個protected native方法;
如果對象實現Cloneable介面的話,需要覆蓋clone方法;
淺拷貝:只複製基本類型;
public class Person implements Cloneable{ private int age ; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() {} public int getAge() { return age; } public String getName() { return name; } @Override protected Object clone() throws CloneNotSupportedException { return (Person)super.clone(); } } View Code
深拷貝:基本類型和參考型別都會複製;
static class Body implements Cloneable{ public Head head; public Body() {} public Body(Head head) {this.head = head;} @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } static class Head /*implements Cloneable*/{ public Face face; public Head() {} public Head(Face face){this.face = face;} } public static void main(String[] args) throws CloneNotSupportedException { Body body = new Body(new Head()); Body body1 = (Body) body.clone(); System.out.println("body == body1 : " + (body == body1) ); System.out.println("body.head == body1.head : " + (body.head == body1.head)); }View Code
可參考:Clone和New哪個更快
Serializable介面序列化:
String類、封裝類、Date類都實現了這個介面;
序列化寫入對象:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("/objectFile")); //建立輸出資料流 out.writeObject("hello"); out.writeObject(new Date()); //寫入對象
還原序列化讀取對象:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("/objectFile")); //建立輸入資料流 String str = (String)in.readObject(); Date date = (Date)in.readObject(); //讀取對象
進一步控制:
定義readObject() 和 writeObject()方法,當ObjectOutputStream對一個對象進行序列化時,如果該對象具有writeObject()方法,則會執行;
private void writeObject(ObjectOutputStream stream) throws IOException{ stream.defaultWriteObject(); stream.writeObject(new Object()); } private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { stream.defaultReadObject(); Object obj = stream.readObject(); }
可參考:JAVA序列化基礎知識Serializable與Externalizable的區別
Serializable序列化時不會調用預設的構造器,而Externalizable序列化時會調用預設構造器的;
二、構造方法
每個類都有一個不含參數的預設構造方法;
若自訂了一個構造方法,則預設的構造方法會消失;
子類在建立對象時,會自動先調用父類的預設構造方法;子類也可以顯示的使用super()調用父類的構造方法;(所以定義類時都會顯示的定義一個空構造方法,防止它丟失了子類調用不了)
Java對象 的建立與構造方法