Interface and abstract class important points
We all know what is interface and abstract class but sometime 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 about it if you are preparing for an interview.
Interface is a common standard/template or contract which can be applied at multiple places where it's sub classes has to follow. A class that implements interface, has to implement interface's declared members.
Important points about interface:
- Support multiple inheritance.
- It only has definition of the methods without 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 consider public.
- Can't declare variables inside interface.
- Only Event, Delegates, Properties and Methods can be declared.
- It's member cannot be static.
- Interfaces cannot contain constructors.
When to use interface?
Answer : When full implementation is require along with reusability. When we have a requirement where classes should have common functionalities, inheriting interface provides guarantee that subclass has 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 abstract class:
- A class can't inherit multiple abstract classes.
- It can have methods with implementation.
- If method marked abstract, you can't declare it's body.
- All the abstract methods of 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 abstract class can be static.
- It can have constructors.
When to use abstract class?
Answer : Classes where common set of functionality require with some added benefits. Abstract class can provide add on feature to 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 has been missed, do let me know.