java--面向对象综合案例一

Cat:

package TESTanimal;



public class Cat {
private int color;
private int height;
public Cat(int color, int height) {
this.color = color;
this.height = height;
}
@Override
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){
return true;
}

}
}
return false;
}


}

Dog:

package TESTanimal;


public class Dog {
public String name;
public int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Dog){
Dog dog=(Dog) obj;
if(dog.name.equals(this.name)&& this.age==dog.age){
return true;
}
}
return false;
}

}

Test:

package TESTanimal;


import org.junit.Test;




public class jTest {
@Test
public void test(){
Cat c1=new Cat(1,2);
Cat c2=new Cat(1,6);
System.out.println(c1.equals(c2));
String s1=new String("hello");
String s2=new String("hello");
System.out.println(s1.equals(s2));
}
@Test
public void test1(){
Dog[] arr=new Dog[7];
Dog dog1=new Dog("金毛",1);
Dog dog2 = new Dog("薩摩耶", 1);
Dog dog3 = new Dog("博美", 2);
Dog dog4 = new Dog("金毛", 2);
Dog dog5 = new Dog("金毛", 1);
Dog dog6 = new Dog("博美", 3);
Dog dog7 = new Dog("博美", 2);

arr[0] = dog1;
arr[1] = dog2;
arr[2] = dog3;
arr[3] = dog4;
arr[4] = dog5;
arr[5] = dog6;
arr[6] = dog7;
int cnt = 0;
for(int i=0; ifor(int j=i+1; jif(arr[i].equals(arr[j])){
cnt ++;
}
//break;
}
}
System.out.println("相同狗的个数是:" + cnt);



}
}

你可能感兴趣的:(java--面向对象综合案例一)