java如何知道返回哪个接口的实现对象? [英] How does java get to know which implementation object of interface to return?

查看:221
本文介绍了java如何知道返回哪个接口的实现对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回答时要温柔,我不是java开发人员(或者一般的开发人员)

Please be gentle while answering, I am not a java developer (or developer in General)

尝试使用java进行xml解析时我遇到了以下内容 -

While trying xml parsing with java I came across following -

NodeList nodelist = document.getElementsByTagName("item");

这里xml dom对象让我根据我提供的标签名称收集所有对象,但返回类型是接口叫 - nodelist。由于接口无法实例化,这对我来说有点意外。

Herein xml dom object let me collect all objects depending on tag name I provide, but return type is an Interface called - nodelist. Since interface can not be instantiated it was a bit surprising for me.

保持断点并调试代码我意识到我实际上获得了实现NodeList接口的类DeepNodeListImpl的对象。

Keeping break point and debugging the code I realized that I actually get object for class DeepNodeListImpl which implements NodeList interface.

这是怎么发生的? java如何知道在上面声明的语句中返回由我的接口object持有的某些实现的对象。

How does this happen? How does java know to return object of "some implementation" held by my Interface "object" in the statement declared above.

还有一件事 - 在阅读java时 api 我发现IIOMetadataNode实现了NodeList但我之前的代码片段没有得到类型IIOMetadataNode的对象

One more thing - while reading the java api I found that IIOMetadataNode implements the NodeList but my previous code snippets does not get me object of type IIOMetadataNode

推荐答案

在getElementByTagName的代码中会有类似

In the code for getElementByTagName there will be something like

NodeList nodeList = new DeepNodeListImpl();
// do something with nodeList
return nodeList;

Java知道使用此类型,因为该方法的代码将明确选择实现。

Java "knows" to use this type because the code for that method will explicitly choose the implementation.

这篇关于java如何知道返回哪个接口的实现对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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