Java常用類學習:Object類(clone方法)
阿新 • • 發佈:2022-03-08
-
Object類:
-
1,Object類是所有類的基類,存放在java.lang包下;
2,這個包下存放的都是Java的系統類,是Java種最基礎的包;
-
-
Ojbect類常用方法:
方法 說明 clone(); 建立與該物件的類相同的新物件; equals(); 比較2個物件是否相等,預設比較的是地址值; finalize(); 當垃圾回收器確定不存在對該物件的更多引用時,物件的垃圾回收器呼叫該方法; getClass(); 返回一個物件執行時的例項類(.class檔案); hashCode(); 返回該物件的雜湊碼值; notify(); 啟用等待在該物件的監視器上的一個執行緒; notifyAll(); 啟用等待在該物件的監視器上的所有執行緒; toString(); 返回該物件的字串表示,預設返回執行時類名+@+物件的hashCode的16進位制數 wait(); 在其他執行緒呼叫此物件的notify()方法或者notifyAll()方法前,導致當前執行緒等待 -
詳細分析:clone()方法
-
1,什麼是clone:
-
-
也就是說,object1和object2是2個獨立的物件,但object2的初始值是由object1物件確定的;
-
實現clone()方法是其中最簡單,也是最高效的手段;
-
-
2,clone()方法的定義:
protected native Object clone() throws CloneNotSupportedException;
-
clone()方法被protected修飾,這樣做是為了避免我們建立每一個類都預設具有克隆能力;
-
clone()方法的通用約定:對於任意一個物件X:
//表示式1
x.clone != x ;//true
//表示式2
x.clone().getClass()==x.getClass();//true //但不是絕對的
//表達3
x.clone().equals(x);//true //但不是絕對的
-
-
3,如何使用clone方法:
-
要使用clone(),需要實現Cloneable介面(空介面);
-
實現它的目的是,表明這個物件是允許克隆的;
-
-
程式碼案例:clone定義類
public class Student implements Cloneable {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
//因為實現了Cloneable介面,所以需要重寫clone()方法
protected Student clone() throws CloneNotSupportedException{
Student stu1=(Student) super.clone();
return stu1;
}
}
-
程式碼案例:測試類
public class ObjectDemo01 {
public static void main(String[] args) {
Student student1=new Student();
student1.setName("張三");
student1.setSex("男");
System.out.println(student1.getName());//張三
System.out.println(student1.getSex());//男
System.out.println("----------------------");
try {
Student student2=student1.clone();//注意:因為有異常丟擲,所以要捕獲異常
//克隆物件後,會把物件當前的屬性值帶過來
System.out.println(student2.getName());//張三
System.out.println(student2.getSex());//男
System.out.println("----------------------");
student2.setName("李四");
student2.setSex("女");
System.out.println(student2.getName());//李四
System.out.println(student2.getSex());//女
System.out.println(student1.getName());//張三
System.out.println(student1.getSex());//男
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
-