What’s the difference between an interface and abstract class with all the abstract methods?
Both interfaces and abstract classes with all abstract methods can be used to define a contract for implementing classes. However, there are some differences:
An interface only defines method signatures and constants, while an abstract class can also have instance variables and concrete methods.
A class can implement multiple interfaces, but can only extend one abstract class.
Here’s an example of an interface:
public interface Vehicle { void start(); void stop(); int getSpeed();}
public interface Vehicle {
void start();
void stop();
int getSpeed();
}
And here’s an example of an abstract class with all abstract methods:
public abstract class Animal { abstract void eat(); abstract void sleep(); abstract void makeSound();}
public abstract class Animal {
abstract void eat();
abstract void sleep();
abstract void makeSound();
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.
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.
After C#8 Interfaces can be used very similarly to Abstract classes including initial definitions, inheritance etc.