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?
Think about this way: If
Catwhere 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:
That code has no knowledge of the concrete type that implements the
Catinterface, but it knows that the object can do everything that theCatinterface requires.