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?
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.
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() { ... } }
Yes, you can 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With