This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The most important reason for using interfaces is to be able to hide the implementation. This way you can provide someone with your interface without him/her having to know what goes on 'behind the scenes'. This means that you can change your implementation without affecting the other person. It also allows for some degree of privacy.
Joined: Dec 25, 2007
Thanks Petrus. The same can be achieved by the abstract class then what functionality does Interface provides that cant be achieved with an Abstract class.
You've already given the reason. Why do you assume there must be a second reason? The first reason is good enough, I think.
"I'm not back." - Bill Harding, Twister
Joined: Feb 20, 2006
This is where design comes in. I like to think that the difference between abstract classes and interfaces is the following:
With abstract classes you create abstractions (as the name implies). This means that you can (using the old car example) define a Car class as abstract, meaning that you know what a car is and what it should do. We all know what a car is, but you can not instantiate, i.e build a car (you will just end up with the framework). You can build a BMW 320i though.
Concerning interfaces, I like to think of them as special abilities. You are a subclass of the abstract class Person. But that is not all, you also play cricket and bowl very well, something not every person can do. Thus you can implement the Bowler interface, but you still inherit from Person.
You may think of this as multiple inheritance and also misuse this by implementing multiple inheritance in this way, but that's just not cricket! That's a hack instead of a good design and that is not what it was meant to do.