2

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 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

3 Comments

You shouldn't describe overloading, then OP asks about overriding. So, please post an example of what you mean, so it is clearer what you mean.
I tried adding code example. But is giving some kind formatting error.
Is there an example comming?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.