Dart Interfaces
Interfaces in Dart
In Dart, interfaces are a way to define a contract that a class must follow. Unlike some other languages, Dart doesn’t have a separate interface
keyword. Instead, every class in Dart can act as an interface. This means that when a class implements another class, it agrees to provide an implementation for all of that class's methods and properties.
Interfaces are particularly useful for defining common behavior across multiple, possibly unrelated classes. You can create an interface by simply creating a class with method definitions and then implementing it in other classes.
Key Points:
- In Dart, any class can be used as an interface.
- To use a class as an interface, another class must implement it.
- The implementing class must provide concrete implementations for all methods and properties defined in the interface.
- Interfaces help define consistent method signatures that multiple classes can adopt, promoting polymorphism and code reusability.
Example of an Interface in Dart
Suppose we want to define an interface for a device that can be turned on and off. We’ll create a Switchable
interface and then have two classes, Light
and Fan
, implement it.
Code Example:
Explanation:
Interface Definition:
Switchable
acts as an interface because it defines two method signatures:turnOn()
andturnOff()
. There is no implementation for these methods withinSwitchable
.
Implementing the Interface:
- Both
Light
andFan
classes implement theSwitchable
interface by using theimplements
keyword. - Each class provides its own concrete implementation for the
turnOn()
andturnOff()
methods.
- Both
Usage:
- In the
main()
function, we create instances ofLight
andFan
and assign them to aSwitchable
type variable. - Each instance then calls
turnOn()
andturnOff()
, using the method signatures defined by theSwitchable
interface, but each with its own specific implementation.
- In the
Polymorphism:
- The
Switchable
type allows us to write code that can handle different types (such asLight
andFan
) in a uniform way, as long as they implement theSwitchable
interface.
- The
Output:
Benefits of Using Interfaces:
- Consistent APIs: Interfaces provide a contract that classes must follow, ensuring consistency across implementations.
- Decoupling and Flexibility: Interfaces help separate the definition of behavior from implementation, making it easier to change one without affecting the other.
- Polymorphism: Interfaces allow you to write more flexible and reusable code, as classes implementing the same interface can be used interchangeably.
Summary:
In Dart, interfaces are defined by creating classes with method signatures and then using the implements
keyword in other classes. Each implementing class must provide concrete implementations for all methods defined in the interface. This approach allows for polymorphism, code reusability, and consistency across different classes in your application.