创建一个返回子类对象的父类

时间:2013-04-26 20:47:47

标签: java inheritance casting parent-child

我正在用Java构建一个基类/父类,它将有几种方法来创建类本身,我想知道是否有任何方法让父类返回子类的实例而不是返回实例然后必须强制转换给孩子的父类?

例如,这是我的父类:

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;
  }
}

如果我基于我的SFObject类创建子类,我的子类中的两个函数仍然会返回一个SFObject(需要转换为我的子类类型)或一个SFObject列表(需要单独使用)强制转换为我的子类类型)。是否有任何方法(可能使用Reflections)让我的子类返回自身的实例而不是SFObjects?

4 个答案:

答案 0 :(得分:1)

您所描述的内容称为 covariant return type

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

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

自Java 1.5以来一直允许这样做。

答案 1 :(得分:0)

如果将子类对象放在父对象中,则调用的方法将从子类运行。但它看起来像表面上的父对象

public class A{
    method 1(){//do some stuff}
    method 2(){//do some stuff}
}

public class B extends A{
    method 1(){super.method 1()
    //do some other stuff}
    method 2(){super.method 2()
    //do some other stuff}
}

public class test{
  A a = new B();

 //any method called on 'a' will come from the child class
 // But 'a' is the parent object

}

答案 2 :(得分:0)

不确定我是否真的理解你的问题是正确的,因为听起来对我说:

class p
{
    public static p createParent()
    {
        return new p();
    }

    public static c createChild()
    {
        return new c();
    }
}

当然,只要想到某种工厂,它就不一定是静态的。

答案 3 :(得分:0)

正如您已经实施的那样,factory methods提出了正确的功能。在子类中,您可以更改返回类型,而不会违反方法声明。您案例的示例如下:

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<? extends 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;
    }

}

class SFObjectChild extends SFObject {

    @Override
    public SFObjectChild CreateFromDiffObject(DiffObject object) {
        SFObjectChild result = new SFObjectChild();
        //...
        return result;
    }

    @Override
    public List<? extends SFObjectChild> CreateListFromQuery(Connection connection,
            String query) {
        return null;//..;
    }

}

这是可以接受的,因为子类的返回类型仍然是一种(分层说话)父类。

请注意java代码约定(camel case中以low开头的方法,例如createFromDiffObject)。