我创建了一个抽象基类。它包含一个应该由任何子类扩展的对象:
public abstract class AbstractParent {
protected AbstractObject subMePlz;
// ... some fields that all subclasses need
public AbstractParent() {
this.subMePlz = createThisInYourExtendedClass();
}
public abstract AbstractObject createThisInYourExtendedClass();
}
抽象对象:
public abstract class AbstractObject {
// ... some fields/methods that all subclasses need
}
我想要的是能够在扩展类中使用扩展字段而无需强制转换:
public class ExtendParent extends AbstractParent {
// .. some unique fields
public ExtendParent(){
super();
}
public ConcreteObject createThisInYourExtendedClass(){
return new ConcreteObject();
}
// what I want to do - no cast
public void doSomethingWithSubMePlzWithoutCastingIt() {
System.out.println(this.subMePlz);
}
// what I end up doing - gotta cast
public void doSomethingWithSubMePlzWithoutCastingIt() {
System.out.println((ConcreteObject)this.subMePlz);
}
}
需要一个比较器会改变我应该如何实现它吗?- 我正在考虑为其子类可以使用的 AbstractObjects 列表的通用比较器。