日期:2014-05-20  浏览次数:20646 次

这句话什么意思?
Effective   java(潘爱民译)   的第二章中有一句话:“静态工厂方法的第三个好处是,与构造函数不同,它们可以返回一个原返回类型的子类型的对象”说的什么意思?比如有类A,有个静态方法method,这句话是说method能够返回A的子类的对象?
如果是这样   怎么实现?

英文版是:“A   third   advantage   of   static   factory   methods   is   that,unlike   constructors,they   can   return   an   object   of   any   subtype   of   their   return   type.”

------解决方案--------------------
构造函数只能返回“当前”类的对象,而静态工厂方法可以返回“当前类”子类的对象
------解决方案--------------------
public class Factory{
  public static Sample creator(int which){
  //getClass 产生Sample 一般可使用动态类装载装入类。
  if (which==1)
    return new SampleA();
  else if (which==2)
    return new SampleB();
  }
}
其中SampleA和SampleB是Sample的子类。