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

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.

Leave a Comment