File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Interfaces" Watch "Interfaces" New topic


Matthew Margolis
Ranch Hand

Joined: Sep 29, 2001
Posts: 32
I would really appreciate it if someone could please explain to me what interfaces are used for and maybe give an example or two(either code or an explanation of a situation). I have read about them in a few java books but I can't seem to grasp the concept, maybe someone here can say something that will make it click.
Rowan Brownlee
Ranch Hand

Joined: Aug 07, 2000
Posts: 97
Hi Matthew
I'll give it a go...
I think of an interface as saying what has to be done, but not how it might be done. An example from the API is the FilenameFilter interface. It contains a method called "accept" which takes a directory and filename as arguments.
The API says that "Instances of classes that implement this interface are used to filter filenames."
It's saying what is required of implementation, but not how this might be made to occur. It's providing a template. It's up to the programmer to flesh out that template with the specific behaviour required.
Eg. I might want to search a directory and find out which files are text files. In this case, I could implement FilenameFilter to select files from a directory which end in the suffix ".txt".
In implementing the interface to meet this end, I'd have to provide some logic within the "accept" method to determine which files are text files. (One way would be to examine each filename argument using the String method endsWith(String suffix))
In another implementation, I might use FilenameFilter to only select files for which I have write permission. (In this case, I'd use methods from the File class to examine each file in the directory to see what permissions are available.)

In both cases, it's the same interface, but I'm implementing different behaviour. Both are implementations of the FilenameFilter interface. Both use the "accept" method which in each case takes a directory and filenames as arguments.
However, in the example implementations, it's the body of the method, the logic that's different. Both examine or filter files within a directory. While one implementation looks for text files, the other looks for write permission.
Matthew Margolis
Ranch Hand

Joined: Sep 29, 2001
Posts: 32
Thanks Rowen, your examples made perfect sense to me and I think I have a decent grasp of the subject now.
Back to the books...
I agree. Here's the link:
subject: Interfaces
jQuery in Action, 3rd edition