Is there a way to say "this method returns this
" using Generics?
Of course, I want to override this method in subclasses, so the declaration should work well with @Override
.
Here is an example:
class Base {
public Base copyTo (Base dest) {
... copy all fields to dest ...
return this;
}
}
class X extends Base {
@Override
public X copyTo (X dest) {
super.copyTo (dest);
... copy all fields to dest ...
return this;
}
}
public <T extends Base> T copyTo (Base dest)
doesn't work at all: I get "Type mismatch: Can't convert from Base to T". If I force it with a cast, the override fails.
Yes, you can return this in Java i.e. The following statement is valid. return this; When you return "this" from a method the current object will be returned.
In java, a method can return any type of data, including objects.
The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
Methods do not return interfaces or classes. They return a reference to an instance (=object) or null (or a primitive value, but let's stick with objects). This reference is usually either stored in a variable or used to call instance methods or access instance members.
You can do something very clever (and akin to what they have done in Scala with the 2.8 collection framework). Declare some interface method that should return "itself" (Note: This
is a type parameter, not a keyword!)
public interface Addable<T, This extends Addable<T, This>> {
public This add(T t);
}
Now declare a level of indirection - a "template" class
public interface ListTemplate<A, This extends ListTemplate<A, This>>
extends Addable<A, This>{
}
public interface List<A> extends ListTemplate<A, List<A>> {
}
Then an implementation of List
has to return a List
from the add
method (I'll let you fill in the impl details)
public class ListImpl<A> implements List<A> {
public List<A> add(A a) {
return ...
}
}
Similarly you could have declard a SetTemplate
and a Set
to extend the Addable
interface - the add
method of which would have returned a Set
. Cool, huh?
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