In what scenarios will you use an abstract class and in what scenarios will you use an interface?
- If you want to increase reusability in inheritance then abstract classes are good.
- If you want to implement or force some methods across classes must be for uniformity you can use an interface.
- So to increase reusability via inheritance use the abstract class as it is nothing but a base class and to force methods to use interfaces.
Some points about Abstract Class:
- We cannot create an object of an Abstract Class.
- An Abstract Class can be inherited with its derived class.
- We can have both concrete and abstract methods but at least one abstract method is compulsory in an Abstract Class.
- An Abstract Class is used as a base class for projects.
- An Abstract Class can inherit another base class and base interfaces.
- The constructor of an Abstract Class can be called through the derived class constructor.
- An Abstract Class should be used for a large project to share the common functionality with its derived class.
- All abstract methods must be implemented in its derived class if inherited.
Some important things about interfaces
- We cannot create an object of an interface; we can only create a reference or Interface Variable.
- An interface will have only abstract methods (method declaration).
- Interfaces support Inheritance, Polymorphism (Overloading, Overriding (using the "new" keyword to hide the interface methods above)).
- We cannot create variables in an interface.
- Only Properties, Indexers, Methods and Events are allowed in an interface.
- A class can inherit multiple interfaces, which is also shown in the snapshot above.
- We cannot create any Access modifiers with Interface Members (like private, public, protected, internal, protected internal, virtual, override, static, abstract etc.)
- The new keyword is allowed in an interface.
- All methods of an interface must be defined in every derived class.
- An interface is good for small or medium level projects.
Abstract Class | Interface |
- An abstract class can have a constructor declaration
| - While an interface cannot do so.
|
- An abstract class is allowed to have all access modifiers for all of its member declarations
| - While in the interface we cannot declare any access modifier (including public) as all the members of an interface are implicitly public.
|
- An abstract class can declare or use any variables
| - While an interface is not allowed to do so.
|
- An abstract class can have non-abstract Methods(concrete methods)
| - While in the case of Interface all the methods have to be abstract.
|
- In an abstract class, all data member or functions are private by default
| - While in interface all are public, we can’t change them manually.
|
Main Difference
An Abstract Class should be used for a large project to share the common functionality with its derived class.
An interface is good for small or medium level projects.