Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interfaces

 
Sully Sylvester
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic