Win a copy of Learning Regular Expressions this week in the General Computing 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 ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Interfaces  RSS feed

 
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.
 
ranger
Sheriff
Posts: 17314
11
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
 
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
Boost this thread!