Win a copy of Grokking Bitcoin this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
  • Carey Brown
  • salvin francis
  • Claude Moore

Interfaces  RSS feed

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.
Posts: 17344
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.

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...
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!