0

I want to make an interface Mergeable that declares a method merge(). A class that implements this will have to implement the method like follows:

SomeObject.java

public class SomeObject implements Mergeable @Override public SomeObject merge(SomeObject other) {...} 

See that the return and parameter type are set to the implementing class. Is there a way to enforce this and how would I set the method signature in the interface?

3
  • 1
    why do you want to enforce a method which returns only one type of object and declare it in interface? Commented Apr 9, 2015 at 18:28
  • 1
    Use generics, something like <T> in your interface. Commented Apr 9, 2015 at 18:28
  • @PrasadKharkar the method should return the type of whichever class implements it. So if I have another class Y it should return Y. Commented Apr 9, 2015 at 18:42

1 Answer 1

7

Look at the Comparable interface for an example. You'll probably have to write something like

interface Mergeable<T> { T merge(T other); } 

...and then anytime you want to accept something Mergeable, write

<T extends Mergeable<T>> void somethingWithMergeables(T merge1) { ... } 
Sign up to request clarification or add additional context in comments.

2 Comments

Why not interface Mergeable<T extends Mergeable<T>>?
That'd work, too, but you'd need to use the same constraint anyway. It doesn't get you much, really.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.