我有很多擴展的子類:如何獲得每班延期的唯一ID?
class FirstImplementation extends Mother { [...]
class SecondImplementation extends Mother { [...]
class ThirdImplementation extends Mother { [...]
我所試圖做的是一個簡單的輕辦法知道Mother
類的兩個實例具有相同的實現:
Mother a = new FirstImplementation();
Mother b = new SecondImplementation();
Mother c = new FirstImplementation();
a.sameKindOf(b); // return false;
a.sameKindOf(c); // return true;
我的想法是建立在每個Mother
例如整數ID字段,只是它在sameKindOf
功能比較:
public class Mother {
private final int ID;
protected Mother(int ID) {
this.ID = ID;
}
public int getID() {
return this.ID;
}
public boolean sameKindOf(Mother other) {
return this.ID == other.getID();
}
}
Mother
的每個擴展都應該用一個精確的ID來調用Mother的構造函數。
我的問題是:有沒有一種方法可以在每次創建新擴展時自動提供不同的ID,還是我必須自己做,並在每個構造器類中給出不同的編號?
如果沒有,是否有更簡單的方法來完成我所要做的事情?
在這種特定的情況下,你不能使用'instanceof'anyway。但是,您可以執行'a.getClass()== b.getClass()'。 –
如果你不想使用instanceof運算符,爲什麼不使用類比較。 '返回this.getClass()== other.getClass();' –
@TeemuIlmonen它會像整數比較一樣快嗎?如果是,請重新發布您的評論作爲答案,我會接受它。 – Aracthor