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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With