Java inheritance with abstract method

2019-07-17 07:39发布

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.

2条回答
Animai°情兽
2楼-- · 2019-07-17 08:06

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.

查看更多
再贱就再见
3楼-- · 2019-07-17 08:11

Yes this is possible. As while overriding a method in the the child class, can always use subclass of the super class declared as an argument in the parent class method. In this example as testForm is a subclass of Form class this will work. Thumb rule is while overriding we can always restrict the hierarchy but not widen the hierarchy.

Suppose parent class of Form class is Document. In TestFormService class populate method we can not use Document as an argument. This will violate overriding rules.

查看更多
登录 后发表回答