用抽象方法进行Java继承 [英] Java inheritance with abstract method
问题描述
我有很多表单类,它们都扩展 Form 。我有一个名为
FormService
的抽象类以及扩展此类的特定表单服务。我想要做的是有一个名为 populate()
的抽象方法,它接受一种形式的表单,从而通过继承调用给定类型的正确服务。
所以我有这样的东西:
public abstract FormService {
public abstract void populate(Form form);
}
public TestFormService extends FormService {
public void populate(TestForm form){
//填充
}
$ b其中
您可以使用泛型:TestForm
是一个扩展Form
。这是可能的,因为我似乎无法得到我想要的影响。
public abstract FormService< F extends Form> {
public abstract void populate(F form);
}
public TestFormService继承FormService< TestForm> {
@Override
public void populate(TestForm form){
// populate
}
}
请注意,使用
@Override
这里只是一个很好的做法,但与问题无关。I have a lot of "form" classes all of which extend
Form
. I have an abstract class calledFormService
and specific form services that extend this class. What I want to do is have an abstract method calledpopulate()
which takes a type of form thus calling the correct service for the given type through inheritance.So I have something like:
public abstract FormService { public abstract void populate(Form form); } public TestFormService extends FormService { public void populate(TestForm form) { //populate }
Where
TestForm
is a type that extendsForm
. Is this possible because I can't seem to get the affect I want.解决方案You could use generics:
public abstract FormService<F extends Form> { public abstract void populate(F form); } public TestFormService extends FormService<TestForm> { @Override public void populate(TestForm form) { //populate } }
Note that the use of
@Override
here is just good practice, but unrelated to the question.这篇关于用抽象方法进行Java继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!