Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
KingTravisG Avatar asked Aug 13 '13 08:08

KingTravisG


1 Answers

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.

like image 199
Tala Avatar answered Sep 21 '22 00:09

Tala