3

我正在用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 列表(需要单独转换为我的子类类型)。有什么方法(可能使用反射)让我的子类返回自身的实例而不是 SFObjects?

4

4 回答 4

1

您所描述的称为协变返回类型

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

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

从 Java 1.5 开始就允许这样做。

于 2013-04-26T22:11:01.963 回答
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

}
于 2013-04-26T20:55:36.457 回答
0

不确定我是否真的理解您的问题是正确的,因为这听起来像这样:

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

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

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

于 2013-04-26T20:56:05.410 回答
0

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

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 代码约定(以低开头的驼峰式方法,例如createFromDiffObject)。

于 2013-04-26T21:05:38.390 回答