You have to put the real implementation of getMessage() into a new concrete class, and delegate to an instance of that class in MyException
and MyRuntimeException
.
class MyExceptionMessage {
public String getMessage() { ... }
}
class MyException extends Exception {
private MyExceptionMessage messager;
public String getMessage() { return messager.getMessage; }
}
class MyRuntimeException extends RuntimeException {
private MyExceptionMessage messager;
public String getMessage() { return messager.getMessage; }
}
You can create an instance of MyExceptionMessage in the constructor of each exception class, or some other way. As you've noted, you're stuck with single inheritance, so there's no way to avoid delegation if you want to reuse the implementation between the two classes.
As Chris has noted, in his answer, a static helper method makes sense, too. At least until your message strategy is complex enough to warrant some instances that you can compose with.
EDIT:
To access the name of the exception class, pass something into to the MyExceptionMessage
constructor - you could pass in the exception object, or its class, or the name of the class. You could also define an interface that your exceptions implement, containing a method that tells the messager whatever it needs to know:
interface Messagable {
public String getMessageFragment();
}
class MyExceptionMessage {
public String getMessage(Messageable) {
return "something" + messagable.getMessageFragment() + "something else";
}
}
class MyException extends Exception implements Messagable {
private MyExceptionMessage messager;
public String getMessage() {
return messager.getMessage(this);
}
}
// class MyRuntimeException would have a similar getMessage() implementation