Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interfaces and return types

Consider I have the following interface:

public interface A { public void b(); } 

However I want each of the classes that implement it to have a different return type for the method b().

Examples:

public class C {    public C b() {}  }  public class D {    public D b() {}  } 

How would I define my interface so that this was possible?

like image 765
Jonathan Avatar asked Mar 10 '10 01:03

Jonathan


People also ask

CAN interface have return type in Java?

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

CAN interfaces have a return type?

By definition of what an interface is it is impossible to return an interface because interfaces cannot be allocated; there cannot be anything to return.

What is the return type of class in Java?

The getReturnType() method of Method class Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.


1 Answers

If the return type must be the type of the class that implements the interface, then what you want is called an F-bounded type:

public interface A<T extends A<T>>{ public T b(); }  public class C implements A<C>{   public C b() { ... } }  public class D implements A<D>{   public D b() { ... } } 

In words, A is declaring a type parameter T that will take on the value of each concrete type that implements A. This is typically used to declare things like clone() or copy() methods that are well-typed. As another example, it's used by java.lang.Enum to declare that each enum's inherited compareTo(E) method applies only to other enums of that particular type.

If you use this pattern often enough, you'll run into scenarios where you need this to be of type T. At first glance it might seem obvious that it is1, but you'll actually need to declare an abstract T getThis() method which implementers will have to trivially implement as return this.

[1] As commenters have pointed out, it is possible to do something sneaky like X implements A<Y> if X and Y cooperate properly. The presence of a T getThis() method makes it even clearer that X is circumventing the intentions of the author of the A interface.

like image 159
Matt McHenry Avatar answered Sep 20 '22 17:09

Matt McHenry