Object類(重寫equals和toString方法)
阿新 • • 發佈:2018-12-14
/* Object類:為所有類的預設根類(基類)
* 1.toString方法:輸出當前物件地址 * 如a=new(); * printf(a)與print(a.toString)相同 輸出地址。 * 注意:可對toString方法重寫,返回想要的值
* 2.equals方法:比較內容 * 如a=new("1","2","3"); * b=new("1","2","3"); * 如何比較a,b相同?a.equals(b)? (錯誤) * 需要對equals重寫: 比較內容(重寫eqals方法的作用是設定你要比較的內容運用if return) * * * 那麼舉一反三 String a=”“; * String b=”“; * 為何可以直接用 a.equals(b)呢?因為String已經對equals進行了重寫 * 方法上加:@Override 檢驗:方法重寫是否符合規範,若不符合會報錯。 */
public class TestObject03 { public static void main(String[] args) { Student s1 = new Student(); s1.name = "路雲華"; s1.age = 30; //System.out.println(s1.toString());//我叫XXX,今年XX歲 System.out.println(s1);//下面這種寫法其實就是預設呼叫toString Student s2 = new Student("王國君",3,'男'); Student s3 = new Student("王國君",3,'男'); Student s4 = new Student("王國君",3,'男'); Student s5 = new Student("王國君",3,'男'); System.out.println(s2==s3);// == 比較的是記憶體地址 System.out.println(s2.equals(s3)); String str = "123"; String str1 = "123"; System.out.println(str.equals(str1)); } } class Student { String name; int age; char sex; public Student(){ } public Student(String name,int age, char sex){ this.name = name; this.age = age; this.sex = sex; } //重寫toString方法 @Override//檢查下面的方法是否是重寫的 public String toString() { return "我叫"+name+",今年"+age+"歲"; } //重寫equals方法 @Override public boolean equals(Object o){ if(this==o){ return true; } if(o instanceof Student){ Student s = (Student) o; if(s.name.equals(this.name)&&s.age==this.age&&s.sex==this.sex){ return true; } } return false; } }