Java Object 对象创建的方式 [ 转载 ]
显式创建
有4种显式地创建对象的方式:
1.构造器:用new语句创建对象,这是最常用的创建对象的方式。
2.反射:运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法。
3.克隆:调用对象的clone()方法。
4.序列化:运用反序列化手段,调用java.io.ObjectInputStream对象的readObject()方法.
下面演示了用前面3种方式创建对象的过程。
1 public class Customer implementsCloneable{2 privateString name;3 private intage;4 publicCustomer(){5 this("unknown",0);6 System.out.println("call default constructor");7 }8 public Customer(String name,intage){9 this.name=name;10 this.age=age;11 System.out.println("call second constructor");12 }13 public Object clone()throwsCloneNotSupportedException{14 return super.clone();15 }16 public booleanequals(Object o){17 if(this==o)return true;18 if(! (o instanceof Customer)) return false;19 final Customer other=(Customer)o;20 if(