How to return an extended object (subclass)? Actually, how to return the exact object which has been passed to a method?

StackOverflow https://stackoverflow.com/questions/22640472

Question

I have an abstract class UIObject looking the following:

public abstract class UIObject {
    private final int tabOrder;

    public UIObject(int tabOrder) {
        this.tabOrder = tabOrder;
    }

    public int getTabOrder() {
        return this.tabOrder;
    }
}

and there are some objects which have UIObject as superclass.

In some service class I've also got a method goTo() which looks like this:

public UIObject goTo(UIObject object) {

    //some fancy code here

    return object;
}

Now, I want to return the specific object which has been passed to the function. (I know, this sounds stupid, but it's got a senseful reason, trust me.) But since the passed objects are all different subclasses of UIObject, this method does not work that way.

I strongy believe, I have done something like this before, thus I think this is an easy thing. Correct me if I'm wrong.

Was it helpful?

Solution

Assuming that you want such invocation of that method to work:

UIObjectSub obj = goTo(new UIObjectSub());

You have to make that method generic:

public <T extends UIObject> T goTo(T object) {
    //some fancy code here
    return object;
}

Now if you invoke that method passing an object of some subclass, the type parameter T will be inferred as that subclass type.

OTHER TIPS

as @Rohit Jain already specified in his answer, method can be generic, but also you can cast objects to child classes. It is called Upcasting

Assume that

SubUIObject extends UIObject {}

As goTo returns a UIObject just upcast it back:

SubUIObject object = (SubUIObject) goTo(new SubUIObject());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top