Java面向物件7——toString和equals
阿新 • • 發佈:2019-02-08
1 Object類
Object類是所有Java類的根基類,如果在類的生命中未使用extends關鍵字指明其基類,則預設基類為Object類
public class Person{
}
等價於
public class Person extends Objects{
}
2 toString方法
- Object類中定義有public String toString()方法,其返回值是String型別,描述當前物件的有關資訊
- 在進行String與其他型別資料的連線操作時(如:System.out.println(“info”+person)),將自動呼叫該物件類的toString()方法
可以根據需要在使用者自定義型別中重寫toString()方法。
API: 推薦所有的類都重寫這個方法
public class TestToString{
public static void main(String[] args) {
Dog d = new Dog();
System.out.println("d:=" + d);//相當於"d:="+d.toString()
}
}
class Dog{
//toString()的重寫
public String toString(){
return "cool dog";
}
}
執行結果:
3 equals方法
- Object類中定義有 public boolen equals(Object obj)方法,提供定義物件是否“相等”的邏輯。
- Object的equals方法定義為: x equals (y)當x和y是同一個物件的應用時返回true否則返回false。
- J2SDK提供的一些類,如String,Date等,重寫了Object的equals方法,呼叫這些類的equals方法,x.equals(y),當x和y所引用的物件是同一類物件且屬性內容相等時(並不一定是相同物件),返回true否則返回false。
可以根據需要在使用者自定義型別中重寫equals方法。
API:
小例子:
public class TestEquals{
public static void main(String[] args){
Cat c1 = new Cat(1,2,3);
Cat c2 = new Cat(1,2,3);
System.out.println(c1==c2);
System.out.println(c1.equals(c2));
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}
class Cat{
int color;
int height,weight;
public Cat(int color,int height,int weight){
this.color = color;
this.height = height;
this.weight = weight;
}
public boolean equals(Object obj){
if (obj == null)
return false;
else{
//如果obj是Cat類的引用
if(obj instanceof Cat){
Cat c = (Cat) obj;
if (c.color == this.color&&c.height == this.height && c.weight == this.weight){
return true;
}
}
}
return false;
}
}
執行結果: