很难用语言解释我所追求的内容,但希望下面的代码示例带有注释就足够了。基本上我希望SubClass sc = new Subclass().method1()
行返回Subclass实例。
public class SuperClass {
public SuperClass method1()
{
//do whatever
return this
}
}
public class SubClass extends SuperClass {
//we inherit method 1
//method2
public SubClass method2()
{
//do whatever
return this
}
}
//succesfully returns instance of Sublass, but...
SubClass sc = new Subclass().method2()
//...the following line returns an instance of SuperClass and not Sublass
//I want Sublass's instance, without having to using overides
//Is this possible?
SubClass sc = new Subclass().method1()
编辑:----------------------------用例场景------------ -------------------
Message myMessage = new ReverseTransactionMessageBuilder()
.policyNo(POLICY_NO) //on ReverseTransactionMessageBuilder
.audUserId(AUD_USER_ID) //on inherited MessageBuilder
.audDate(new Date()) //on inherited MessageBuilder
.processNo(EProcessConstants.FINANCE_MANUAL_ADJUSTMENT.getProcessCd()) //on inherited MessageBuilder
.serviceName("finance.ProcessReversalCmd") //on inherited MessageBuilder
.create(); //create is overridden so this is ReverseTransactionMessageBuilder
首先要注意的是sbrattla方式允许我以任何顺序调用这些.audDate()。xxx()方法。使用上面的类构造,你被迫最后调用sublcass上的方法(或使用一个非常丑陋的演员)
答案 0 :(得分:7)
您需要执行以下操作:
public class SuperClass<T> {
public T method1() {
return (T) this;
}
}
public class SubClass extends SuperClass<SubClass> {
public SubClass method2() {
return (SubClass) this;
}
}
您可以在“Generics Introduction”中阅读有关Java Generics的更多信息,但简要说明您要告诉SuperClass将返回的实例强制转换为代表您定义的类型的T.在这种情况下,它是SubClass。
答案 1 :(得分:0)
我认为您可以使用如下通用方法:
class Parent {
public <T extends Parent> T instance() {
return (T) this;
}
}
class Child extends Parent {
}
class Test {
public static void main() {
Child child = new Parent().instance();
}
}