Reputation: 67
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
Reputation: 1074495
Any ideas? I want to solve this without the use of casting.
Your options are:
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