我有一个带有许多扩展子类的类:
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,还是我必须自己做一次,在每个构造函数类中给出不同的编号?
如果没有,是否有更简单的方法来完成我要完成的工作?
最佳答案
不会
public boolean sameKindOf(Mother other) {
return this.getClass().equals(other.getClass());
}
做这份工作?