3

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

10
  • You don't need <E extends Input> for the method, E is already parametrised. Commented Jun 8, 2014 at 8:09
  • Also, what is ButtonInput? Commented Jun 8, 2014 at 8:10
  • @OliCharlesworth I've removed what you've said and now when I'm compiling lint gives me a warning of unchecked cast. And ButtonInput is just another class the represents a graphic button Commented Jun 8, 2014 at 8:12
  • But ButtonInput isn't in the code you've shown us. Please construct a complete test-case. Commented Jun 8, 2014 at 8:13
  • shouldn't you return "Input" instead of "E" ? I suggest you to watch this video: sites.google.com/site/io/effective-java-reloaded , presentation here: 14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/… Commented Jun 8, 2014 at 8:20

1 Answer 1

6

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

That's really smart, I'll try doing it
Solved my problem. It's a bit tricky but working just fine and removes the warnings . Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.