aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Interfaces" Watch "Interfaces" New topic
Author

Interfaces

Sully Sylvester
Greenhorn

Joined: Jan 05, 2005
Posts: 6
Ok i understand all the rules of interfaces and that they help to with javas no existence of multiple inheritance. But i dont understand why this is so or why they are neccessary or an example in which you would use them.

any help would be much appreciated.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Interfaces is a big key to Polymorphism. You can code to an interface and never need to know exactly which implementation class you are using. So if you have three possible implementation that depend on who is calling it. Instead of writing three methods each to take a different implementation, you can write one method that takes the interface and calls interface methods to produce your results.

It helps quite a bit in a lot of Design Patterns to have this functionaily.

There are some interfaces that are needed as "Marker" interfaces like Serializable, so that it is known that this class can be passed over RMI, etc.

Hope that helps a bit.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
To expand on Mark's explanation, you can store objects of different types in a collection if they all implement the same interface. The collection itself would be a collection of references to the interface type, not the object type. That's a powerful tool!

For example, if you have an interface called "drivable" that has one method, drive, you could have the following classes implement drivable: car, bicycle, motorcycle. Then, you could have collection of drivable objects and iterate through the collection calling the drive method on each object within the collection without having to worry about what type the object is. By each object having implemented the drivable interface, the contract guarantees that each object in the collection of drivables will implement the drive method.

Hope that helps...


Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
 
Don't get me started about those stupid light bulbs.
 
subject: Interfaces