We all know what is an interface and abstract class but sometimes we forget or get confuse while comparing it. This happens mostly in an interview. This is very common and most important question asked by interviewer despite you are fresher or experienced.
Therefore, I am listing here all the important points of interface and abstract class. This will be helpful if you simply want to brush up on it if you are preparing for an interview.
An interface is a common standard/template or contract which can be applied at multiple places where it’s subclasses has to follow. A class that implements an interface, has to implement interface’s declared members.
Important points about the interface:
- Support multiple inheritances.
- It only has a definition of the methods without the body.
- All the declared method has to be implemented in the derived class.
- Access modifier can’t be used. By default, all the members are considered public.
- Can’t declare variables inside interface.
- Only Event, Delegates, Properties, and Methods can be declared.
- Its member cannot be static.
- Interfaces cannot contain constructors.
When to use interface?
Answer: When full implementation is to require along with reusability. When we have a requirement where classes should have common functionalities, inheriting interface provides a guarantee that subclass has the complete feature of it.
Example: Consider IVehicle interface. This provides standard or functionality like Steering, Doors, Wheels which subclass must have.
An abstract class is a special kind of class that cannot be instantiated.
Important points about the abstract class:
- A class can’t inherit multiple abstract classes.
- It can have methods with implementation.
- If a method marked abstract, you can’t declare it’s body.
- All the abstract methods of an abstract class has to be implemented.
- Access modifiers can be marked for its member.
- It can have Variable, Events, Delegates, Properties and Methods declaration.
- Only complete member of the abstract class can be static.
- It can have constructors.
When to use abstract class?
Answer: Classes where a common set of functionality requires with some added benefits. An abstract class can provide add-on feature to the child class.
Example: Contrary to IVehicle interface, abstract class Vehicle can have same features like Steering, Doors, Wheels with additional feature like AirBag which can be utilized based on child class.
http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo?rq=1 http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface http://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class?lq=1
If you think any points have been missed, do let me know.