Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to say "method returns this" in Java?

Tags:

java

generics

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.

like image 913
Aaron Digulla Avatar asked Jul 07 '09 08:07

Aaron Digulla


People also ask

Can we return this from a method?

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.

Can a method return a reference Java?

In java, a method can return any type of data, including objects.

What is Java Lang reflect method?

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.

Can methods return interfaces?

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.


1 Answers

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?

like image 168
oxbow_lakes Avatar answered Oct 21 '22 09:10

oxbow_lakes