有4種顯式地創建對象的方式:
1.用new語句創建對象,這是最常用的創建對象的方式。
2.運用反射手段,調用java.lang.Class或者java.lang.reflect.Constructor類的newInstance()實例方法。
3.調用對象的clone()方法。
4.運用反序列化手段,調用java.io.ObjectInputStream對象的readObject()方法.
下面演示了用前面3種方式創建對象的過程。
public class Customer implements Cloneable{
private String name;
private int age;
public Customer(){
this("unknown",0);
System.out.println("call default constructor");
}
public Customer(String name,int age){
this.name=name;
this.age=age;
System.out.println("call second constructor");
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public boolean equals(Object o){
if(this==o)return true;
if(! (o instanceof Customer)) return false;
final Customer other=(Customer)o;
if(this.name.equals(other.name) && this.age==other.age)
return true;
else
return false;
}
public String toString(){
return "name="+name+",age="+age;
}
public static void main(String args[])throws Exception{
//運用反射手段創建Customer對象
Class objClass=Class.forName("Customer");
Customer c1=(Customer)objClass.newInstance(); //會調用Customer類的默認構造方法
System.out.println("c1: "+c1); //打印name=unknown,age=0
//用new語句創建Customer對象
Customer c2=new Customer("Tom",20);
System.out.println("c2: "+c2); //打印name=tom,age=20
//運用克隆手段創建Customer對象
Customer c3=(Customer)c2.clone(); //不會調用Customer類的構造方法
System.out.println("c2==c3 : "+(c2==c3)); //打印false
System.out.println("c2.equals(c3) : "+c2.equals(c3)); //打印true
System.out.println("c3: "+c3); //打印name=tom,age=20
}
}
以上程序的打印結果如下:
call second constructor
call default constructor
c1: name=unknown,age=0
call second constructor
c2: name=Tom,age=20
c2==c3 : false
c2.equals(c3) : true
c3: name=Tom,age=20
從以上打印結果看出,用new語句或Class對象的newInstance()方法創建Customer對象時,都會執行Customer類的構造方法,而用對象的clone()方法創建Customer對象時,不會執行Customer類的構造方法。(區別)
除了以上4種顯式地創建對象的方式以外,在程序中還可以隱含地創建對象,包括以下幾種情況:
1.對於java命令中的每個命令行參數,Java虛擬機都會創建相應的String對象,並把它們組織到一個String數組中,再把該數組作爲參數傳給程序入口main(String args[])方法。
2.程序代碼中的String類型的直接數對應一個String對象,例如:
String s1="Hello";
String s2="Hello"; //s2和s1引用同一個String對象
String s3=new String("Hello");
System.out.println(s1==s2); //打印true
System.out.println(s1==s3); //打印false
執行完以上程序,內存中實際上只有兩個String對象,一個是直接數,由Java虛擬機隱含地創建,還有一個通過new語句顯式地創建。
3.字符串操作符“+”的運算結果爲一個新的String對象。例如:
String s1="H";
String s2=" ello";
String s3=s1+s2; //s3引用一個新的String對象
System.out.println(s3=="Hello"); //打印false
System.out.println(s3.equals("Hello")); //打印true
4.當Java虛擬機加載一個類時,會隱含地創建描述這個類的Class實例.