是否可以在Java中创建接口的对象? [英] Is it possible to create an object of an interface in java?

查看:313
本文介绍了是否可以在Java中创建接口的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,接口仅包含方法类型,名称和参数.实际的实现在实现它的类中完成.在这种情况下,如何创建接口实例并像使用类对象一样使用它呢?有许多这样的接口,例如 org .w3c.dom.Node .

In java, an interface contains only the method type, name and parameters. The actual implementation is done in a class that implements it. Given this, how is it possible to create an instance of a interface and use it as if it were a class object? There are many such interfaces, such as org.w3c.dom.Node.

这是我正在使用的代码:

This is the code that I am using:

DocumentBuilderFactory fty = DocumentBuilderFactory.newInstance();
fty.setNamespaceAware(true);
DocumentBuilder builder = fty.newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(result.getBytes());
Document xmldoc = builder.parse(bais);
NodeList rm1 = xmldoc.getElementsByTagName("Subject");
Node rm3 = rm1.item(0);

推荐答案

您永远不会创建 just 接口的实例.您可以具有该接口类型的field/parameter/local变量,但这很好-分配给此类变量的值将始终为null或对该接口的某些具体实现的实例的引用.关键是只处理接口的代码不需要关心实现是什么.

You never create an instance of just the interface. You can have a field/parameter/local variable of that interface type, but that's fine - the value that is assigned to such a variable will always be either null or a reference to an instance of some concrete implementation of the interface. The point is that code which deals only with the interface shouldn't need to care what the implementation is.

一个很好的例子是 Collections.shuffle(List) -我可以提供任何列表实现,并且它将仅使用在接口中声明的方法. 实际对象将始终是某些具体实现的实例,但是shuffle方法不需要了解或关心.

A good example is Collections.shuffle(List) - I can provide that any list implementation, and it will only use the methods declared in the interface. The actual object will always be an instance of some concrete implementation, but the shuffle method doesn't need to know or care.

这篇关于是否可以在Java中创建接口的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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