Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: Phone Interview
Java !!! Well M not a very much of JAVA Coder unlike C++ but My Answer would be like.
Abstract Class in More flexible than interface . means, i will put some logic which later on I can change easily in the derived classes.. Well that says the saying " In interface by Default all methods are abstract". So only Definition in Interface.
However coming to this question. here both the implementation are more or less same. Except the fact that if I want a method Say get1() to have some bydefault logic, I can't do in interface, i need to have Abstact Class.
but along side I am okei with your rest of the responses !!!
Your responses all are very valid. But what he might be looking is the purpose. If you want define the core abilities of your class use abstract classes, if you want to define the peripheral abilities of the class use interface. eg: AbstractList, vs Comparable, You can have a person class its core feature is not comparing but some other business logic, one of its ability is also that it can compare. On the other hand, a list is concrete implemention of absctract list, there isn't much else the list can/should do.
One can easily add new methods in the abstract class without requiring the subclasses to implement it. This is not possible in case of an interface. Code change required to add new methods can be very small for abstract class whereas in case of interface all the implementing classes have to be modified.
The way I look at abstract classes is that they are just like other classes with 2 exceptions
1. They cannot be instantiated (biggest exception).
2. They can contain abstract methods.
The reason I use abstract class is when the class can have a lot of member functions that can be inherited by many classes but the class in itself has no meaning to instantiate it! Also they work like an "interface" in the sense that you can have abstract methods.
I think that technically speaking the two are the same. As all the methods of the abstract class are abstracts (no base definition of any method), the abstract class is behaving like the interface ie subclassing MyAbstract will require to "implement" all three methods (as implementing MyInterface will require implementing the three methods).
Xali Beut
A basic difference i can think of is that
- salvo4u May 22, 2012* Interfaces are used at places when u don't know anything.
* Abstract classes are used in places when u know some components and do not know some. Everything that u do not know is made abstract.