Naimish Makwana
Interface vs abstract class with all abstract methods?

What’s the difference between an interface and abstract class with all the abstract methods?

By Naimish Makwana in C# on Jan 16 2023
  • Tuhin Paul
    Feb, 2023 14

    Both interfaces and abstract classes with all abstract methods can be used to define a contract for implementing classes. However, there are some differences:

    1. An interface only defines method signatures and constants, while an abstract class can also have instance variables and concrete methods.

    2. A class can implement multiple interfaces, but can only extend one abstract class.

    Here’s an example of an interface:

    1. public interface Vehicle {
    2. void start();
    3. void stop();
    4. int getSpeed();
    5. }

    And here’s an example of an abstract class with all abstract methods:

    1. public abstract class Animal {
    2. abstract void eat();
    3. abstract void sleep();
    4. abstract void makeSound();
    5. }

    Note that in the second example, the Animal class do not have any instance variables or concrete methods. If it did, those would have to be implemented by any non-abstract subclass.

    • 1
  • Satyaki Chakraborty
    Jan, 2023 30

    An interface and an abstract class with all abstract methods both provide a blueprint for implementing classes, but there are some key differences between the two:

    Inheritance: An interface can be implemented by multiple classes, whereas an abstract class can only be inherited by a single class.

    Accessibility: Members of an interface are public by default, while members of an abstract class can have any accessibility level.

    Implementation: In an interface, the implementing class must provide implementations for all methods, while in an abstract class, some or all methods can be left abstract and implemented by subclasses.

    Properties and fields: Interfaces can only have method signatures and events, while abstract classes can have fields, properties, and instance variables.

    Constructors: An interface cannot have a constructor, while an abstract class can have a constructor.

    In general, you should use an interface if you want to specify a contract that can be implemented by multiple classes, and use an abstract class if you want to create a base class that provides some default behavior.

    • 1
  • Munib Butt
    Jan, 2023 26

    After C#8 Interfaces can be used very similarly to Abstract classes including initial definitions, inheritance etc.

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS