Olivier J.
Olivier J.

Reputation: 3165

OOP with Java : avoiding to duplicate code

I would like to override toString() method of several personnal exceptions which are of type Exception or RuntimeException.

Say that I would like to display test with toString() methods for both Exception and RuntimeException sub-classes. I have to override toString() one time only so.

How can I do it because Java doesn't support multi inheritance please ? I just don't want to write 2 times toString() method for both type of exceptions...

Example :

public class SubClassOfException extends Exception {

    ...

   @Override
   public String toString() {   
      return "test";
   }

}

My goal is to create SubClassOfRuntimeException and benefit of the custom toString() method of SubClassOfException because RuntimeException is a sub-class of Exception.

Is there a way to do it or I have to duplicate toString() code into SubClassOfException and SubClassOfRuntimeException ?

Upvotes: 1

Views: 280

Answers (1)

Desty
Desty

Reputation: 2776

Since your SubClassOfException is hierarchical on the same level as RuntimeException, you cannot share the toString() method via inheritance.

But you don't need to duplicate the code either, if both toString() methods in your concrete exception types delegate the actual string building to a common "exception string builder". I mean something like

class ExceptionPrinter {
    public static String exceptionToString(Exception e) { ... }
}

and in both exception classes

@Override
public String toString() {
    return ExceptionPrinter.exceptionToString(this);
}

Upvotes: 4

Related Questions