我想比较不同类的对象“name”属性。有人会解释我怎么做吗?这里的代码。
class Cat implements Comparable<Cat>{
String name;
Cat(){
super();
}
Cat(String name){
this.name = name;
}
@Override
public int compareTo(Cat obj){
return this.name.compareTo(obj.name);
}
}
class Dog extends Cat{
String name;
Dog(String name){
this.name = name;
}
}
public class Compare {
public static void main(String[] args) {
Cat oCat1 = new Cat("Meow");
Cat oCat2 = new Cat("Purr");
Dog oDog1 = new Dog("Rex");
int result = oCat1.compareTo(oDog1);
System.out.println(result);
}
}
答案 0 :(得分:1)
拥有这个超级课程
class NamedPet implements Comparable<NamedPet> {
private String name ;
public NamedPet(String name) {
this.name = name;
}
public int compareTo(NamedPet otherPet){
return this.name.compareTo(otherPet.name);
}
}