2017-04-15 99 views
0

我想比較不同類的對象「名稱」屬性。應該有人向我解釋如何做到這一點?這裏的代碼。是否可以比較兩個不同的java對象?

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

有類共享相同的接口,一個具有'公共字符串的getName()'方法。 –

回答

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); 
    } 
}