你能用Java实例化一个接口吗? [英] Can you instantiate an Interface in Java

查看:76
本文介绍了你能用Java实例化一个接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能用Java实例化一个接口

Can you instantiate an Interface in Java

我知道快速回答是不。
但是有些东西我不太了解。

I know the quick answer is "no". But there is something I am not understanding well.

这里发生了什么:

SharedPreferences是一个公共接口:

SharedPreferences is a public Interface :

http://developer.android.com/reference/android/content/SharedPreferences.html

但是我们没有使用这个界面,因为我在书中已经读过,我们不创建一个类并实现SharedPreferences。 \

However we do not use this interface as I have read about in the books, we do not create a class and implement SharedPreferences. \

相反,我们使用这样的API:

Instead we use this API like this:

 SharedPreferences pref = Context.getSharedPreferences("some value", 0);

http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,%20int)

那么这段代码到底发生了什么?

So what is really happening in this code ?

我认为它与getSharedPreferences()一样,正在创建一个我们可以使用和操作的SharedPreferences对象。

I think its like getSharedPreferences() is creating a SharedPreferences object which we can then use and manipulate.

但是SharedPreferences是一个接口......我被告知你必须实现接口而不是创建它们的对象。

But SharedPreferences is an Interface ... and I was told you have to implement Interfaces not create object of them.

这是什么在Java?

非常感谢所有指针

(我还在尝试学习)

跟随问题。

当我查看Java API时,我看到一个类为定义为公共接口。
如何知道何时实现该接口或何时从中创建此类对象?

When I look at a Java API and I see a class as defined as Public Interface. How do I know when to implement that interface or when to create this type of object from it ?

推荐答案

你永远不能在java中实例化一个接口。但是,您可以通过接口类型引用实现接口的对象。

You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface.

所以发生的是 getSharedPreferences 返回实现该接口的对象。返回对象的类型并不重要。重要的是它实现了该接口的所有方法,因此它可以用作 SharedPreferences

So what is happening is that getSharedPreferences returns an object that implements that interface. The type of the returned object is not important. What is important is that it implements all the methods for that interface, so it can be used as an SharedPreferences

这篇关于你能用Java实例化一个接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆