Reputation: 7799
For example, I have a some class:
public class Test<T> {
public T setField() {
return this;
}
}
Of course, it's an incorrect class. But can I write it some else? (to it hasn't errors). P.S. I know that I can write an abstract method to override it in the child class. But I ask about the generic class only (in the its class body only).
Upvotes: 3
Views: 1482
Reputation: 122489
It is not possible for something like this to work safely in general in Java. this
is only known to be an instance of Test<T>
, which is not known to be a subtype of T
, the type you want to return. There is no bound on T
that can guarantee that this
is an instance of T
. No matter what bounds you give T
, for any type that you can use for T
that satisfies those bounds (call it X
), I can just define a new class (unrelated to X
) that extends Test<X>
, and you cannot return an instance of this class as X
, because it is not an X
.
Upvotes: 1
Reputation: 49646
If you want to return an instance of your class (this
), it does simply by using the class declaration (Test<T>
):
public Test<T> setField() {
return this;
}
If you want to return a type of a generic parameter, look at @wero's answer.
Upvotes: 8
Reputation: 33000
Casting this to T
makes only sense if you use a recursive type bound. Still you need to add a cast and suppress the warning:
abstract class Test<T extends Test<T>> {
@SuppressWarnings("unchecked")
public T setField()
{
return (T)this;
}
}
Define derived classes like:
public class DerivedTest extends Test<DerivedTest> { ... }
and now this works without any casts needed in the client code:
DerivedTest d = new DerivedTest().setField();
Upvotes: 6