aspose file tools*
The moose likes Beginning Java and the fly likes What is an interface? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is an interface?" Watch "What is an interface?" New topic
Author

What is an interface?

Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
Hi all,
I am having trouble understanding exactly what an interface is. Books give me some hard to understand definition.
Can anyone explain, in layman's terms what an interface is in Java and in general?

Thanks in advance
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1688
    
  12

An interface in java is basically a class that has empty methods. Examples of this include Map, Set, List, and Runnable. You can't use interfaces without a class that implements them. The easy way to use an interface is to find a class in the Java API that implements it (like HashMap for Map). A more advanced way to use an interface is to write a class that implements the interface. This is done by making sure every method that the interface includes is accounted for and has code written for it.

Another possibility is to write your own interface... and classes that implement it. For example you might be creating a zoo application. You would maybe have an interface Animal... each animal could be classified by type... like the Mammal class would have different methods as the Amphibian class, but both would implement the methods included in Animal, say for example eat(), sleep(), poop(), etc. You could add methods to the Mammal class, like giveMilk(), growHair().... and to the Amphibian class like swim(). In order to write a class that implements an interface you need to remember to account for all the methods.


When you do things right, people won't be sure you've done anything at all.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Janeice:

Actually, what you're describing sounds more like an abstract class than an interface. Maybe a better illustration would be some thing like this:

As you can see, the Flyer interface describes a contract for behavior. The implementation details are specific to the class (obviously, a Boeing 747 doesn't fly like a Bat), but all three types can fly().

John.
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1688
    
  12

John,

I extrapolated my response from this....

Interface Tutorial

Maybe you can set me straight?
To me, it looks like you have a class with empty methods that you need to create code for when you implement the interface.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Janeice:

It's better to think of an interface as a type that describes behavior rather than a class that has empty (i.e. abstract) methods. Interfaces can't be instantiated (abstract classes can't be instantiated directly, but are instantiated when concrete subclasses are instantiated), so there's no 'object' there.

John.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

An interface is simply a contract between itself and the implementing class. An interface has no method bodies. The implementing class will complete the methods. There are a ton of good reasons to "code to interfaces". Here is a quick example:







Now, in a particular system there might be a reason why Email or SMS is preferred. And internally this has been determined. But all you might care about is sending the message and not having to worry yourself with how that message is sent....



The MessengerFactory would determine which implementation to use for you. I hope that helps make a bit more sense.


GenRocket - Experts at Building Test Data
Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
So what exactly does an interface do?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Jon Manson wrote:So what exactly does an interface do?


Nothing.
Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
Is it no different than making a class?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Jon Manson wrote:Is it no different than making a class?


See my Messenger example.
Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
I'm sorry about not getting this, but I still don't understand.
What do you mean by - a contract between itself and the implementing class
What is the contract?
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1688
    
  12

The "contract" is that the implementing class MUST have code for ALL the interface methods.

It basically says "in order to be an implementation of (insert interface name here), the implementing class must do these things"

i.e. such as in Gregg's example, "in order to be an implementation of Messanger, the implementing class must provide code for sendMessage()"

John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Jon Manson wrote:I'm sorry about not getting this, but I still don't understand.
What do you mean by - a contract between itself and the implementing class
What is the contract?


The contract is that a class that implements an interface has to implement all of the methods of that interface. I my example above, all three classes implemented the Flyer interface, so they all had fly() methods. For a more involved example, look at the Javadoc for the List interface, and ArrayList, a class that implements it.

John.
Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
Thanks, but how is an interface different to an abstract class?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
There's a contract. Your method promises to play ball if you play ball. You send it a valid number and it sends back its square root. Promise. That promise constitutes the contract.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Jon:

Abstract classes are real classes that exist in class hierarchies. Abstract class cannot be instantiated directly, but are instantiated when their concrete subclasses are. Interfaces are never instantiated, and there will never be an object of an interface type.

John.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
You can instantiate an interface as an anonymous class . . .
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Jon Manson wrote:Thanks, but how is an interface different to an abstract class?


An abstract class can have functional methods. An interface cannot.

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
An interface class IS an abstract class.

public abstract interface ForumReader {


}

When the programmer leaves out the 'abstract' keyword from the code, the compiler will interpret the keyword 'interface' and will automatically add the internal code for 'abstract'. This occurs prior to bytecode generation. This is part of advanced source code parsing and beyond the scope of "Beginning Java".
Jon Manson
Greenhorn

Joined: Oct 31, 2009
Posts: 10
So, abstraction is when a class is broadly defined and cannot be instantiated.
Is an interface a class which has all methods in it abstract?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Another explanation as to why interfaces are a good thing....

Imagine a system you built that sends Emails (see the messenger example I already gave). Imagine you didn't use interfaces and everywhere in your code you had calls to a concrete EmailMessenger class. The client comes back a few months later and says, you know, we really should send SMS's instead of Emails. Since you didn't use an interface for your message sending abilities, you now must refactor dozens of classes and methods (possibly) where you have used EmailMessenger to send an email and replace all these instances with an SmsMessenger.

If you had coded to interfaces, all you would have had to do was replace the code in MessengerFactory.getMessenger() to give you an appropriate messenger instance. Then the rest of your code would not need to be modified at all.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Jon Manson wrote:So, abstraction is when a class is broadly defined and cannot be instantiated.
Is an interface a class which has all methods in it abstract?


Yes and no. Abstraction does not mean it can't be instantiated. As was stated, anonymous classes can, but that's a more complex scenario you shouldn't concern yourself with yet. In essence an interface is a class in which all its methods are abstract, but you don't use the abstract keyword. So if that helps you understand the rules a bit better, I see no problem with that. However, to be precise with the definition

In its most common form, an interface is a group of related methods with empty bodies.


See here for some good examples.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
James Clarks wrote:An interface class IS an abstract class.

public abstract interface ForumReader {


}

When the programmer leaves out the 'abstract' keyword from the code, the compiler will interpret the keyword 'interface' and will automatically add the internal code for 'abstract'. This occurs prior to bytecode generation. This is part of advanced source code parsing and beyond the scope of "Beginning Java".


However, you can't have a concrete top-level class extend an interface, which makes them different than 'regular' abstract classes. I just tried this:


Apparently java (or its error messages, at least) doesn't think of interfaces as classes: I got the error "The type List<String> cannot be the superclass of Sandbox; a superclass must be a class".

John.
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

John de Michele wrote:
James Clarks wrote:An interface class IS an abstract class.

public abstract interface ForumReader {


}

When the programmer leaves out the 'abstract' keyword from the code, the compiler will interpret the keyword 'interface' and will automatically add the internal code for 'abstract'. This occurs prior to bytecode generation. This is part of advanced source code parsing and beyond the scope of "Beginning Java".


However, you can't have a concrete top-level class extend an interface, which makes them different than 'regular' abstract classes. I just tried this:


Apparently java (or its error messages, at least) doesn't think of interfaces as classes: I got the error "The type List<String> cannot be the superclass of Sandbox; a superclass must be a class".

John.


Well, yea, that' what the implements keyword is for. ;) You can't extend from something that has no real behavior. Interfaces only describe the behavior.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Jon Manson wrote:So what exactly does an interface do?


Interface is just another name for a totally abstract class (that cannot be changed into being partly abstract or even fully concrete). In principle Java could scrap interfaces and use classes only.

If there were classes only, you wouldn't need two keywords for inheritance, extends and impelements, you could just say,

class A inherits B, C, D {}

But the Java inheritance model would still require that only one of B, C and D would carry implementation, the rest would need to be totally abstract. This wouldn't be necessary of course if Java didn't have this limitation and allowed inheritance of implementation from multiple classes.

If an interface is just a totally abstract class with a special name, then why was it introduced in the first place? There are two main reasons. One is pedagogical. It's easier to handle a feature if it has a name. The other is to make a virtue out of a necessity. The Java inheritance model requires that all but one inherited class is totally abstract so let's call it something special. Then people tend to forget that it really is a limitation.

So interfaces simply are totally abstract classes that are guaranteed to stay totally abstract. They've been given a special name for pedagogical reasons, and to make a virtue out of a necessity.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is an interface?