java怎麼創建對象
A. 在java中創建對象到底有多少種方法
Java中創建對象的四種方式
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
}
}
除了以上4種顯式地創建對象的方式以外,在程序中還可以隱含地創建對象,包括以下幾種情況:
1.對於java命令中的每個命令行參數,Java虛擬機都會創建相應的String對象,並把它們組織到一個String數組中,再把該數組作為參數傳給程序入口main(String args[])方法。
2.程序代碼中的String類型的直接數對應一個String對象。
3.字元串操作符「+」的運算結果為一個新的String對象。
4.當Java虛擬機載入一個類時,會隱含地創建描述這個類的Class實例.
B. Java如何創建對象
Java有5種方式來創建對象:
1、使用 new 關鍵字(最常用):
ObjectName obj = new ObjectName();
2、使用反射的Class類的newInstance()方法:
ObjectName obj = ObjectName.class.newInstance();
3、使用反射的Constructor類的newInstance()方法:
ObjectName obj = ObjectName.class.getConstructor.newInstance();
4、使用對象克隆clone()方法:
ObjectName obj = obj.clone();
5、使用反序列化(ObjectInputStream)的readObject()方法:
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
ObjectName obj = ois.readObject();
}
C. JAVA創建對象有哪幾種方式
Java中創建對象的四種方法 收藏Java中創建對象的四種方式x0dx0a1.用new語句創建對象,這是最常見的創建對象的方法。x0dx0a2.運用反射手段,調用java.lang.Class或者java.lang.reflect.Constructor類的newInstance()實例方法。x0dx0a3.調用對象的clone()方法。x0dx0a4.運用反序列化手段,調用java.io.ObjectInputStream對象的 readObject()方法。x0dx0a第一種最常見