java之Object類介紹

一、Object類是全部java類的基類java

若是在類的聲明中未使用extends關鍵字指明其基類,則默認基類爲Object類,ex:this

public class Person{spa

    ~~~~~code

}對象

等價於blog

public class Person extends Object{class

    ~~~~~引用

}方法

二、Object類之equals方法im

①、Object類中定義有:

  public boolean equals(Object obj)方法。

    提供定義對象是否相等的邏輯。

②、Objec的equals方法  定義爲:x.equals(y)當x和y是同一個對象的應用時返回true,不然返回false.

③、J2SDK提供的一些類,如String,Date等,重寫了Object的equals()方法,調用這些類的equals方法,x.equals(y),當x和y所引用的是同一類對象且屬性內容相等時(並不必定是相等的對象),返回true不然返回false.

④、能夠根據須要在用戶的自定義類型中重寫equals()方法。

public class TestEquals{
    public static void main (String args[]){
        Cat cat1 = new Cat(1,2,3);
        Cat cat2 = new Cat(1,2,3);
        System.out.println(cat1 == cat2);
        System.out.println(cat1.equals(cat2    ));
        
        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;
    
    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{
            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;
    }
}

運行結果:

相關文章
相關標籤/搜索