为了让equals方法来判断2个对象的内容是否相同。
重写了equals方法。

class Test2 {
    
public static void main(String args[]) {
        Dog d1 
= new Dog(1);
        Dog d2 
= new Dog(1);
        Dog d3 
= new Dog(2);
        System.out.println(d1 
== d2);//false
        System.out.println(d1.equals(d2));//true
        System.out.println(d1.equals(d3));//false
    }
}

class Dog {
    
private int i;
    Dog(
int i) {
        
this.i = i;
    }
    
public boolean equals(Object o) {
        
if(o != null) {
            
if(o instanceof Dog) {  //判断传过来的 对象o 是否属于Dog类型的
                Dog d = (Dog)o;  //把对象o强制转换成Dog对象类型
                if(this.i == d.i) {
                    
return true;
                }
            }
        }
        
return false;
    }
}
posted on 2008-12-07 07:15 天长 阅读(355) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: