Originally posted by John Davis:
If the implementor of a Java interface must implement all of the methods in the interface, of what use (other than the possible inheritance of some final private members) is the interface? Why not just provide all of the methods in the class and skip implementing the interface?
I guess i would tackle your second question first. Why not just provide all of the methods in the class and skip implementing the interface?
1. Once you see that a particular class implements an Interface, you are sure that that class will have a certain set of methods. If two or more classes implement the same interface , you can clearly see the relationship -- this will not be possible if we adopt your approach. For example, just by checking that a class implements the interface Runnable, i can very well decide that it qualifies as a parameter to the
Thread constructor. I need not scan the whole code to find whether the run method exists.
2. Let us say your interface has 5 methods and your class implements the interface but needs only 2 of them, you can give an empty body for the rest of the 3 methods,but of course
you should define them too. An example might be the implementation of the WindowListener interface. You will not need all the window events. But still, if you implement the WindowListener you have to atleast give a blank body within all the rest of the methods other than the one you need(let us say, Windowclosing event) Fortunately, a WindowAdapter helps out in this case.
3. One more important case in favour of Interfaces is multiple inheritance -- one parent , many children. This can be achieved directly in C++ -- one class can inherit as many classes as it prefers. But in java,a class can extend only one class (singleinheritance). Of course, there will be a lot of instances when we will need the functionality of more than one class. That is when interfaces step in. A class can implement any number of interfaces -- so in effect, you can achieve multiple inheritance .
4. Now to your first question -- the compulsion that you should implement all the methods is a matter of consistency . As has been explained by Cindy in the first response, if the interface is a car -- when you implement the interface, you should implement everything associated with a car,you cannot choose to have the driving() method and omit the startingEngine() method()!!!
Hope this helps,
------------------
Regards,
Shree
[This message has been edited by shree vijay (edited January 04, 2001).]