Categories
.NET English OOP

Abstract modifier uses and examples

Abstract modifier is added to something that is not usable or incomplete. In classes it means that the abstract class could be used only for inheritance or sub-classing (in java).

Real life examples of things that’re similar to abstract class

An abstract class for cars: this class may contain general features of a car, like number of doors because any car may have at least one door, color is also needed as any car may have a color, engine size and fuel type is also should be found in any car.

Now we can inherit (create sub-class) from car abstract class:

Interfaces vs Abstract classes

One of the common questions in interviews is about the difference between interfaces and abstract classes. Interfaces is some form for multiple inheritance in java and dot net. You can inherit from class A and class B in interface class C easily combining features from both of them. There are some disadvantages of using multiple inheritance, like to have more complex code. The most significant advantage of using interfaces is to create unique classes that have the features of multiple classes together.

Previously we created a class for Salon car that is inherited from abstract car class. Now we want to create another class for huge trucks and another one for military cars that have shields. An example of an interface is when we want to create a big salon car with shield.

In summary:

  1. Interfaces are used for inheriting from multiple classes, while abstract classes are created to be inherited.
  2. Both interface and abstract class have similar class components building, like there’s no implementation in interface and abstract methods.
  3. Interface can be instantiated but abstract classes could not.

Leave a Reply

Your email address will not be published. Required fields are marked *