Dart Interfaces : Extending vs Implementing | Difference between Extends & Implements keyword
Extending :
Extending is used to create a subclass that inherits the properties and methods of a superclass.
It establishes an "is-a" relationship between the subclass and the superclass. For example, if you have a class
Animal
and another classDog
that extendsAnimal
, you're saying thatDog
is a specific type ofAnimal
.The subclass can access all non-private members (fields and methods) of the superclass.
You use the
extends
keyword to indicate that a class inherits from another class.
Example:
class Animal { void eat() { print('Animal is eating'); } } class Dog extends Animal { void bark() { print('Dog is barking'); } }
Implementing :
Implementing is used to declare that a class will provide specific behavior as defined by an interface.
It establishes a "can-do" relationship between the implementing class and the interface.
An interface in Dart is effectively a class with abstract methods and possibly no implementation.
A class can implement multiple interfaces.
You use the
implements
keyword to declare that a class implements one or more interfaces.
Example :
abstract class Flyable { void fly(); } // Define a class named Bird which implements the Flyable interface class Bird implements Flyable { @override void fly() { print('Bird is flying'); } }