简体   繁体   中英

Java Methods returning Interface types

I've seen related questions, but the answers only skirt the heart of the answer I'm looking for.

I have the following line of code (and it compiles and runs without error):

Document doc = dbuilder.parse(myXmlFile);

where Document is the interface org.w3c.dom.Document and parse() is a method from javax.xml.parsers.DocumentBuilder

When I then executed

System.out.println(doc.getClass().getName());

its output is

com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl

which, I assume, means that DeferredDocumentImpl implements the Document interface, and that when I execute methods against my doc variable, I'm actually executing the methods of DeferredDocumentImpl.

My questions are:

  1. Is that above assumption correct, that is, am I indeed executing the implemented methods of that DeferredDocumentImpl class?

  2. An interface can be implemented by any number of classes, and assuming that org.w3c.dom.Document is indeed implemented by multiple classes, why did the Document type returned by parse() get cast as the DeferredDocumentImpl class, and not one of the other classes that implements Document ?

  3. Assuming that 2. above is some kind of 'default' or 'priority' type-assignment, where do I verify - and possibly change - that assignment?

  4. How would I override the type-assignment I describe in 3. above at the level of the code itself?

As I say, I've searched dutifully for this, but nothing seems to give me answers to these specific questions... much appreciated.

am I indeed executing the implemented methods of that DeferredDocumentImpl class?

yes

An interface can be implemented by any number of classes, and assuming that org.w3c.dom.Document is indeed implemented by multiple classes, why did the Document type returned by parse() get cast as the DeferredDocumentImpl class, and not one of the other classes that implements Document?

You would need to read the code to determine why that library returned that implementation. I wouldn't be surprised if its the only implementation that library has.

Note: org.w3c.dom.Document is an API standard interface, a library which implements this API need only provide one implementation. A library doesn't have to create an implementation from another library.

Assuming that 2. above is some kind of 'default' or 'priority' type-assignment, where do I verify - and possibly change - that assignment?

Yes, change the object the library creates by modifying the source of the library.

How would I override the type-assignment I describe in 3. above at the level of the code itself?

Checkout a copy of the source, change it and built it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM