Hi all....i am new to Java here....can anyone tell me what is the significance of interfaces....why do i have to override their methods from scratch....i just don't get it....i mean i can write my own methods inside my class without the need to implement an interface with an empty methods....can anyone please get it straigtened at for me ....many thanks
Yes it can seem a bit confusing at first but believe me interfaces are really useful. There's loads of help/explanation of interfaces available online if you do a quick google for it so I'm not going to rewrite stuff that's already easily available. But in a nutshell interfaces define a behaviour all implementing class must have. These classes may have no other relaionship to each other other than they all implement a particular interface. For example: If you wanted to write some code that ran a task you could write a method eg public void runTask(Task myTask) that accepted a Task Object and called it's run method. This is fine but your code is limited to running Task objects (or subclasses of Task) and if you want to run an Object that isn't inherited from Task you would have to provide an overloaded method for every extra Class type that you may want to run. This limits the code to types you currently know about as well as filling your class with loads of overloaded methods. An alternative approach is to rewrite your runTask() method to take any Object that implements the Runnable interface eg public void runTask(Runnable myTask). The Interface Runnable defines a run() method so all classes which implement Runnable must have a public void run() method so you can safely call run() on any object that is passed into the runTask method. You don't need to know what the object type is after all you are only interested in a behaviour the object has ie that it can be run.
say I am partnering with other companies. i don't really care what kind of object they pass me, I just want to be able to call certain methods on it. I tell them "your object must implement THESE methods with THESE signiatures". They do this by implementing the interface in their class, and my code simply uses references to that interface.
I write my code to accept something that garantees to implement those methods (i.e. my interface). Their objects do. Life is good.
I go to the bahamas. That other company goes bankrupt. I now partner with a NEW vendor, and say "hey, your objects must implement these methods".
I don't leave the beach. They implement the methods, and I don't have to touch my code. [ August 09, 2007: Message edited by: Fred Rosenberger ]
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Aug 22, 2006
Thanks Tony...that was really usefull....i still got to dig in deeper...thanks again