Very Strange Tushar..... I had the same question. I found the answer in "The Complete Reference"--by Patrick Naughton. This is the answer I got(mind you, it is just one of the advantages of Interfaces, I am sure, there are many more, as interfaces are widely used in real-time programming).
Accessing multiple implementations of an interface through an interface reference variable is the most powerful way that Java achieves run-time polymorphism
Pg.247 Just think, for eg. by creating a reference variable of MyPetInterface, you could access the eat() methods of classes Cat, Dog, Fish, Parrot etc. I hope I make myself clear Also, interfaces get over the inconveniences caused by multiple inheritence in other languages. Hope that this helps Rebecca
Originally posted by tushar limaye: what is the need of interface? what is exact use of it?
Tushar, You can also use interface for a couple of other things. I'll give you two examples. One is a really simple one, bit can be really handy. Example One: Constants If you have four or five different files let us say that all need to use the same constants one way to give them access is to put all the constants in an interface like so:
Then, you can implement your interface and have access to all those constants in your file, like so:
Example 2. Okay, there is another cool use for them, but this one is a LOT more indepth. You can write your class so that it can fire of events to other classes that listen for those events. Those other classes would implement some interface you create so that you can fire the events to them. This is probably way to complex for this forum, so I won't get into it here, but once you've written more and more Java programs you'll find interfaces become a very cool concept that let you do a lot of things. So, I hope this helps some. Jason
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop