Duke
Duke

Reputation: 67

Pass an instance of the subclass to a method and use it later within that method

I have a method (prepareErrorMessage) that accepts objects of type ErrorMessagePojoSuperclass. However, I only pass subclasses of ErrorMessagePojoSuperclass as arguments:

public class ErrorMessagePojoBundle extends ErrorMessagePojoSuperclass {}

public class Tester {
    ErrorMessagePojoBundle empb = new ErrorMessagePojoBundle();
    prepareErrorMessage(empb);

    public void prepareErrorMessage(ErrorMessagePojoSuperclass errorMessagePojo) {   
        String errorStatusMsg = messageConverter.convertXMLToString(errorMessagePojo);                             
    }
}

The class ErrorMessagePojoBundle has more methods than its superclass.

I need to make sure that when the line of code is running messageConverter.convertXMLToString(errorMessagePojo), messageConverter processes an instance of the subclass - in this case the object empb. Any ideas? I want to solve this without the use of casting. Thank you.

Upvotes: 0

Views: 66

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Any ideas? I want to solve this without the use of casting.

Your options are:

  1. Defining an interface with the necessary method, having the subclass implement it, and using that interface as the parameter type rather than the superclass.
  2. Changing the parameter type to the subclass, not the superclass.
  3. instanceof and casting (not usually what you want to do).

1 and 2 are basically just variants of each other.

In your example code, there's no reason for prepareErrorMessage to accept the superclass rather than the subclass (or an interface), since the only thing it does can only be done with the subclass (or something implementing the same interface).

Upvotes: 1

Related Questions