![](/img/trans.png)
[英]Constructor with values from inherited abstract class, which implements an interface
[英]How change the parameter from an inherited class that implements an interface?
我有一个接口和一个实现该接口的类,如下所示:
public interface DocumentDAO<T>{
public long insert (T doc);
}
public class PostgreSQLDocumentDAO implements DocumentDAO<Document>{
public long insert(Document doc){}
protected void insertDocument(Document doc){}
}
我想重写PostgreSQLDocumentDAO
的insert方法,将参数从Document更改为Page ,其中Page是扩展Document的类。
我想要这样的东西:
public class PostgreSQLPageDAO extends PostgreSQLDocumentDAO{
public long insert(Page doc){
super.insertDocument(page);
//specific implementation goes here
}
}
我怎么能得到这个?
更新:上面的代码是不正确的,因为称为Inserter
的类使用接口DocumentDAO
。 当它调用insert方法时,即使它是PostgreSQLPageDAO对象,它也会调用insert方法来插入Document,因为该方法是继承的。
我想做一种方法,当Inserter
类调用insert方法时,它使用插入页面的方法。 这样,我想我需要覆盖PostgreSQLDocumentDAO
的insert (Document doc)
。
这里有两个选择。
然后您将其更改为
public class PostgreSQLDocumentDAO<D extends Document> implements DocumentDAO<D>
和
public class PostgreSQLPageDAO extends PostgreSQLDocumentDAO<Page>
2.您不能修改PostgreSQLDocumentDAO
然后,您需要使用以下方法重载并覆盖PostgreSQLPageDAO中的insert方法:
// Override
@Override
public long insert(Document doc){
if (!(doc instanceof Page))
throw new IlegalArgumentException("insert only accepts Page");
super.insert(doc);
}
// Overload
public long insert(Page page){
super.insert(page);
}
我没问题。
由于Page
是从Document
派生的,因此您可以简单地传递Page
来代替Document
。
如果需要在派生类的方法中进行特殊处理,则可以检查Document
是否是instanceof
Page
并执行所需的操作。
当然,前提是您不能更改接口/类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.