Java – generics – method return type as extension class
•
Java
I tried to do this in Java 6:
abstract class CurrClass{ public <T extends CurrClass> T setField (String str) { return this; } }
Compiler complaint error: type mismatch: cannot convert from currclass to t
Add an actor's work and issue a warning: "return (T) this;"
Is there a clearer grammar to do this? Why do actors need?
Solution
The return type is more restrictive than the returned object This is why the compiler generates errors (and subsequent warnings) Consider this:
class A extends CurrClass {} class B extends CurrClass {} ... A myObject = new B().setField("stringhere");
This is perfectly legal in your settings, but will result in ClassCastException
This is why we usually return only types that are more stringent than signature requirements
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码