Java Abstract Classes: Returning "this" pointer for derived classes

design-patterns, java

Solution

is there anyway to return the "this" pointer without having to override the method in every single derived class?

Yes, look at the option 1 below.

There are several ways you can do here:

Cast the result to the derived class

Override it in subclasses

Change return type to void. Since you're invoking a method on an object, you already have a pointer to it.

Problem

I am trying to write some custom exceptions with helper methods for setting the variables like this: ``` public class KeyException extends RuntimeException { protected String Id; protected KeyException(String message) { super(message); } protected KeyException(String message, Throwable cause) { super(message, cause); } public String getId() { return keyId; } public KeyException withId(final String Id) { this.Id = Id; return this; } } ``` However, in my derived classes, I cannot use the "withId" method as it only returns the base class - is there anyway to return the "this" pointer without having to override the method in every single derived class?

Original source