KingTravisG KingTravisG - 1 month ago 9
Java Question

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

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?

Answer

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:

  1. Cast the result to the derived class

  2. Override it in subclasses

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