This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
What is the use of having interfaces when we can dirtectly implement the required method in a class?
Sayed Ibrahim Hashimi
Ranch Hand
Joined: May 17, 2001
Posts: 148
posted
0
Because Java doesn't support Multiple inheritance a class can not extends more than one class. To support some form of it Java has "interfaces". Interfaces don't have any data memebers only method definitions. So lets say that I created an interface that included the method draw. I would know that all classes that implements a class would have the draw method. So I can treat those Objects generically. Hope this helps.
Originally posted by Ibrahim Hashimi: Interfaces don't have any data memebers only method definitions.
Interfaces can have "data members".
Note that the data member of the interface is (implicitly) final - you can't change it (go ahead and try - I dare ya). As a general tip for finding lots of great information, try a search on the JavaRanch forums for topics that might have been discussed previously. One is sure to find lots of useful information. The search page link is at the top right of this page. Good Luck.
A good example of the benefits of Interfaces is employed by the utility classes. An example.
The map reference variable is declared as a Map, but points to a specific implementation: HashMap. Recall that the keys in a HashMap are not returned in any order. Now suppose we want to impose some order on the keys in our Map. All we have to do is change the first line to:
Since we declared map as a Map, the other lines of code do not break, and we now have a Map which returns its keys in a specific order. [In actual fact, this example works if the keys we add to the Map implement Comparable. Otherwise we would need to supply an implementation of the Comparator interface in the TreeMap constructor.] Hope this helps