开发者

parent class to return subclass

开发者 https://www.devze.com 2023-04-06 11:40 出处:网络
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 Subclas

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.

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. With the class construct above you are forced to call the method on the sublcass last (o开发者_如何学运维r use a really ugly cast)


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. In this case, it's 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();
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消