This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
While I was giving interview I was asked...
Why can't we replace the interface with fully abstract class (i.e. abstract class with all methods as abstract). I was asked what's the advantage of using interface in this case instead of
fully abstract class.
I could not give a proper answer for the same..
Can somebody give me a proper reason for the same.
The answers above are right. But not the reason. Abstract classes have their reason for being in the language. So do interfaces.
Abstract classes are those classes which are not ready yet. They have a few methods a few variables but still are not ready. Thus you cannot make objects of these classes. Some examples of places where your design would hav abstract classes would be if you are making a platform independant file access class with your own implementation of the buffer and io management. The methods which do the buffer and io management (if you want to write them per platform), each platform will havei its own implementation. So a subclass which derives from your class will simply write the methods and start working. But without these, you cannot instantiate your class. Hence your class is abstract.
Or in terms of text book examples, an automobile is an abstract class. It can drive , honk etc. How it does this depends on which subclass of the automobile you look at.
One of the places where interfaces are used is where you have certain requirements which a particular object which you use in your class has to meet. You are not writing the code for this class. You are using the object. But you need it to perform a few tasks. You can then define these tasks in an interface. The creator of this class will then implement your interface and gurantee you that your requirements with respect to the methods has been met.
Since both end up having a similar contract, they both can be used in each others place at times. But bear in mind they have different reasons for being in the picture.