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.”
如果是这样 怎么实现?英文版是:“A third advantage of static factory methods is that,unlike constructors,they can return an object of any subtype of their return type.”
if class C extends class A
if class D extends class BAFactory.getAInstance() may return an instance of class A, B, C, or D.
AFactory.getAInstance() 是类A的方法吗?如果是,这个静态方法怎么写才能返回B的实例呢?
如果你知道,就回答我的问题,不要在书上抄来的东西,就以为懂了。
可以举个例子吗?(静态工厂方法可以返回“当前类”子类的对象)
public static Sample creator(int which){
//getClass 产生Sample 一般可使用动态类装载装入类。
if (which==1)
return new SampleA();
else if (which==2)
return new SampleB();
}
}
其中SampleA和SampleB是Sample的子类。