Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a parent class that returns child class objects

I'm building a base/parent class in Java that's going to have several methods for creating the class itself and I'm wondering if there's any way to have the parent class return instances of the child class instead of returning instances of the parent class that then have to be cast to the child?

For example, here's my parent class:

public abstract class SFObject
{
  // Variables
  protected String mID;
  protected String mName;

  // Function called to create ourselves from a DiffObject
  public abstract SFObject CreateFromDiffObject(DiffObject object);

  // Function called to create a list of ourselves from a query
  public List<SFObject> CreateListFromQuery(Connection connection, String query)
  {
    // Run the query and loop through the results
    ArrayList<SFObject> objects = new ArrayList<SFObject>();
    for (DiffObject object : connection.Query(query))
      objects.add(CreateFromDiffObject(object));

    return objects;
  }
}

If I create a child class based on my SFObject class, the two functions in my child class will still return an SFObject (that needs to be cast to my child class type) or a list of SFObjects (that need to be individually cast to my child class type). Is there any way (maybe using Reflections) to have my child class returns instances of itself as itself and not as SFObjects?

like image 405
Harry Muscle Avatar asked May 01 '26 00:05

Harry Muscle


1 Answers

What you are describing is known as a covariant return type.

Class A {
    A getInstance() { ... }
}

Class B extends A {
    @Override
    B getInstance() { ... }
}

This has been allowed since Java 1.5.

like image 116
Jim Garrison Avatar answered May 02 '26 12:05

Jim Garrison