问题描述
我刚看到这样的成员函数:
I just saw a member function like this:
public Cat nextCat(GameState state);
但Cat是这样的界面:
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?
推荐答案
想一想:如果 Cat
这里是普通班,当你想要调用某些方法时,你会关心什么完全?
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);
该代码不知道实现 Cat的具体类型
接口,但它知道对象可以执行 Cat
接口所需的所有内容。
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.
这篇关于函数返回接口意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!