简体   繁体   中英

Return subclass from generic abstract class java

So, I have this abstract class that represents an Input type object -

public abstract class Input<E>

And I have two classes that extends it, one is ButtonInput and the other is TextInput. Both extend Input so it doesn't really matter. I'll use TextInput just to explain.
This is the TextInput class defention:

public class TextInput extends Input<TextInput>

What I'm trying to do is to return this as E (TextInput in this case)-

public E setTextColor(Color color) {
        this.colorText = color;
        return (E)this;
    }

So, If I call for example:

new TextInput().setColor(Color.black)

It should return TextInput. It is working but, it shows the following warning -

warning: [unchecked] unchecked cast
return (E) this; required: E
found: Input
where E is a type-variable:
E extends Object declared in class Input

In relation to the following line of code -

 return (E) this;

Does anybody knows how to solve it?
Thanks

This is a pattern I've used in the past to solve this type of issue in abstract builder patterns. It relies on an abstract me() method that is overridden to return a reference to the concrete object.

abstract class Foo<T> {
    protected abstract T me();

    public T baz() {
        return me();
    }
}

class Bar extends Foo<Bar> {
    protected Bar me() {
        return this;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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