简体   繁体   English

父类返回子类

[英]parent class to return subclass

Its hard to explain in word what I'm after but hopefully the code example below with the comments is sufficient. 很难用言语解释我所追求的,但是希望下面带有注释的代码示例就足够了。 Basically I want the SubClass sc = new Subclass().method1() line to return the Subclass instance. 基本上,我希望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()

EDIT: ----------------------------usecase scenario------------------------------- 编辑:----------------------------用例场景------------------ -------------

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

First thing youl notice is that sbrattla way allows me to call these .audDate () .xxx() methods in any order. 您首先注意到的是sbrattla方法允许我以任何顺序调用这些.audDate().xxx()方法。 With the class construct above you are forced to call the method on the sublcass last (or use a really ugly cast) 使用上面的类构造,您不得不最后调用sublcass上的方法(或使用非常丑陋的强制转换)

You would need to do something like: 您将需要执行以下操作:

public class SuperClass<T> {

  public T method1() {
    return (T) this;
  }

}

public class SubClass extends SuperClass<SubClass> {

  public SubClass method2() {
    return (SubClass) this;
  }

}

You can read more about Java Generics in the " Generics Introduction ", but briefly explained you're telling SuperClass to cast the returned instance to T which represents a type you define. 您可以在“ 泛型简介 ”中阅读有关Java泛型的更多信息,但简要说明一下,您是在告诉SuperClass将返回的实例转换为T,该实例表示您定义的类型。 In this case, it's SubClass. 在这种情况下,它是SubClass。

I think you can use generic method like the following: 我认为您可以使用如下通用方法:

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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM