gpt4 book ai didi

java - 父类返回子类

转载 作者:行者123 更新时间:2023-11-29 10:06:13 26 4
gpt4 key购买 nike

很难用语言来解释我在追求什么,但希望下面的代码示例和注释就足够了。基本上,我希望 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 上的方法(或使用非常丑陋的强制转换)

最佳答案

您需要执行以下操作:

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 泛型的更多信息,但简要说明了您要告诉 SuperClass 将返回的实例转换为代表您定义的类型的 T。在这种情况下,它是子类。

关于java - 父类返回子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7512917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com