用抽象方法进行Java继承 [英] Java inheritance with abstract method

查看:129
本文介绍了用抽象方法进行Java继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多表单类,它们都扩展 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 called FormService and specific form services that extend this class. What I want to do is have an abstract method called populate() 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 extends Form. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆