任何類的直接父類或間接父類數組
對於引用數據類型,打印變量名的時候自動調用toString方法,默認打印的是地址,ide
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); //默認打印的是地址 }
若是不想打印地址,那麼就在相應的子類裏面重寫子類this
public class Student { private String name; public Student(String name) { this.name = name; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; } }
public class TestStudent { public static void main(String[] args) { Student student=new Student("張三"); System.out.println(student); } }
沒有重寫toString方法時,默認打印的是地址3d
重寫toString方法時,打印的是裏面的內容code
本質對象
調用(若是是基本數據類型,則比較內容,不是則默認比較地址,例如bject的equals源碼以下:)blog
public boolean equals(Object obj) { return (this == obj); }
但String類(final數組)中的equals方法是重寫了Object的equals方法,比較是其中每一個字符的內容接口
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
用途:使一個新對象中有已經創建對象的數據內容(克隆)get
在object類中,clone方法的訪問權限是protectd源碼
protected native Object clone() throws CloneNotSupportedException;
子類要想調用clone方法,必需要有如下步驟
1.extends Object
2.且實現Cloneable接口
3.重寫(override)clone方法(Alt+Enter快捷鍵)
4.調用到處理重寫clone方法的throws拋出的CloneNotSupportedException異常
public class Student extends Object implements Cloneable{ private String name; public Student(String name) { this.name = name; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
public class TestStudent { public static void main(String[] args) { Student student=new Student("張三"); System.out.println("student學生的信息爲: "+student); //try...catch用來接收調用clone()方法時,經過throws拋過來的異常 try { Student student1=(Student) student.clone();//想把student對象裏面的信息賦值給student1 System.out.println("student1學生的信息爲: "+student1); } catch (CloneNotSupportedException e) { e.printStackTrace();//打印異常處理的信息 } finally { } } }