Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/5699427/what-does-it-mean-for-a-function-to-return-an-interface

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...