Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes interface method confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface method confusion" Watch "interface method confusion" New topic

interface method confusion

Tsehau Chao

Joined: Jul 20, 2008
Posts: 6
Hi, after going through various code and APIs, one problem lead to another and right now I'm so confused that I'm not even sure if this is the right question!

I was given some sample code based on JDOM to work on XML files. It uses the collection framework which I am not familiar with (I was taught with JDK 1.4). In these sample codes (and many tutorials), I noticed many instances where an interface reference type invoked an interface method, yet I was unable to track down exactly which class implemented that interface.

In my n00b understanding, an interface method must be overridden somewhere! It does not make sense to use an abstract method. It is very frustrating and confusing to not be able to find that hidden class. Here is the code snippet in question:

String filename = xmlfile;
SAXBuilder builder = new SAXBuilder();
Document doc = File(filename));

XPath oPath = XPath.newInstance("//Location");
List lPath = oPath.selectNodes(doc);
System.out.println("XML has "+ lPath.size() + " locations");
// why can lPath call size()? Who's overridding it?

Iterator i = lPath.iterator();
while(i.hasNext()) {
Element eLocation = (Element);
// same question with hasNext() and next()!

Thanks in advance!

(years later I'll be laughing at this, I know!)
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
You can find out the actual name of the concrete class by calling getClass().getName() on an instance of the class. But in general, it doesn't really matter. The purpose of the interface is to abstract away the need to depend on particular concrete classes, your code only depends on the interface that that class implements. The actual concrete class could some well-known public class, a private class, or even an anonymous class. It doesn't really matter, You know what methods you can call because you know what interface the object implements.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

jodeci, welcome to JavaRanch.

Please check your private messages for an administrative matter. You can see them by clicking My Private Messages.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: interface method confusion
It's not a secret anymore!