Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for a function to return an interface?

Tags:

java

I just saw a member function like this:

public Cat nextCat(GameState state);  

But Cat is an interface like this:

public interface Cat {         void makeCat(GameState state); } 

So I am confused as to how to interpret this. I know what it means when something returns an object or a primitive. But what does it mean to return an interface? How to use this function's return value?

like image 380
jason Avatar asked Apr 18 '11 06:04

jason


People also ask

What is return type of interface?

If an interface is defined to be the return type of a method then instances of classes derived from that interface can be returned. The benefit of doing that is no different from returning objects of classes derived from a class.

What is the return type of interface in Java?

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() { ... } }

Can we return an interface in C#?

Yes, you can return an interface.


2 Answers

Think about this way: If Cat where a regular class, what exactly would you care about when you wanted to call some methods on it?

You'd care about the method definitions: their names, their argument types, their return values. You don't need to care about the actual implementation!

Since an interface provides all of that, you can call methods on it, just as you can on a regular class.

Of course, in order for the method to actually return some object, there needs to be some class that implements that interface somewhere. But what class that actually is or how it implements those methods doesn't really matter to the code that gets that object returned.

In other words, you can write code like this:

Cat cat = nextCat(GameState.STUFF); cat.makeCat(GameState.OTHER_STUFF); 

That code has no knowledge of the concrete type that implements the Cat interface, but it knows that the object can do everything that the Cat interface requires.

like image 143
Joachim Sauer Avatar answered Sep 22 '22 22:09

Joachim Sauer


This function returns an object of a class which implements the Cat interface. The implementation details (for this concrete class) are up to you, as long as you implement all the methods of the Cat interface for it.

like image 35
Dhruv Gairola Avatar answered Sep 24 '22 22:09

Dhruv Gairola