Cole Petersen
Cole Petersen

Reputation: 65

Returning an object of the same type as the function's caller

I have two classes, one which extends the other. Most of the functions in the parent class return either itself (after modifying the object that called the function) or a new object of the same type. The child class is supposed to share these functions, however its should return an object of the child type.

The obvious solution to this issue is to just override every function and convert them into an object of the child type, but I don't want to do this every time I make a child class.

I did some searching and found some solutions using generic functions. However, those either need an extra Class<T> argument or can potentially cause a type casting error.

Is there a way to create a function in a parent class such that an object of either parent or child type can return itself or an object of the same type?

Upvotes: 2

Views: 874

Answers (1)

casablanca
casablanca

Reputation: 70701

The obvious solution to this issue is to just override every function and convert them into an object of the child type, but I don't want to do this every time I make a child class.

If you have a special method to create a new instance of the child type, you can reuse this in all your other methods. You'll still have to override this one method in each child class but it's better than overriding every method:

public abstract class Parent<T extends Parent<T>> {
  protected abstract T newInstance();

  public T doSomething() {
    T instance = newInstance();
    // do something with instance
    return instance;
  }

  public T doSomethingElse() {
    // do something with this
    return this;
  }
}

public class Child extends Parent<Child> {
  protected Child newInstance() {
    return new Child();
  }
}

Child.doSomething now returns a Child without having to override doSomething.

Upvotes: 2

Related Questions