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:
Note that the use of
@Override
here is just good practice, but unrelated to the question.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.