public static void main(String[] args) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder db=factory.newDocumentBuilder(); Document document=db.parse("city.xml");

NodeList list=document.getElementsByTagName("地区");  //1

Node node=list.item(0);                               //2
 
System.out.println(node.getTextContent());
}问题1:代码中的NodeList 和 Node 是个接口,接口中不是只有方法体不能有实现的嘛?java中怎么就可以使用呢? 
      比如NodeList 如果说返回的对象是NodeList的类型,那肯定也是NodeList的子类或者new过NodeList返回的吧,但是
      API中NodeList没有子类而且是个接口也不能被new啊底层封装?java中到底是什么原理??请高手给讲解一下调用原理...先谢了。

解决方案 »

  1.   

    NodeList list=document.getElementsByTagName("地区");  这个返回的是一个实现了NodeList接口的类。NodeListImpl..之类的东西。不是NodeList的子类。是实现类
      

  2.   

    相当于
    List<String> tmp = new ArrayList<String>();
      

  3.   

    这是java中的多态,NodeList是一个接口没错,但是document.getElementsByTagName("地区"); 返回的确实实现了NodeList接口的一个具体实现类,所以我们可以把这个返回值看做是NodeList来操作。
    举个例子:
    苹果,我可以看做是个接口。而红苹果我们可以看做是苹果的具体类。那我们可以说红苹果是苹果。就正如
    Map<String, String> map = new HashMap<String, String>();
    map = new TreeMap<String, String>();一样