I am trying to achieve this in Java 6 :
abstract class CurrClass{
public <T extends CurrClass> T setField (String str) {
return this;
}
}
Compiler complains with error : Type mismatch: cannot convert from CurrClass to T.
Adding cast works, with warning :"return (T) this;"
Is there a cleaner syntax to do this? Why is the cast needed?
The return type is more restrictive than the object being returned. That's why the compiler generates the error (and subsequent warning). Consider this scenario:
class A extends CurrClass {}
class B extends CurrClass {}
...
A myObject = new B().setField("stringhere");
This is perfectly legal in your setup, but will result in a ClassCastException.
That's why usually we only return a more restrictive type than the signature calls for.
Why is the cast needed?
Because this is the CurrClass and the method setField() want to return a extending class of it.
Super super = new Sub(); //it's fine, no casting is needed
Sub sub = new Super(); //error!! -->what you do
Is there a cleaner syntax to do this?
If you want to SubClass s = super.setField("");, you have to cast.
But we often do Super s = sub.setField(""); for polymorphism can bring us convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With