Skip to main content

Command Palette

Search for a command to run...

Dart Interfaces: Extending vs Implementing | Difference between Extends & Implements keyword

Published
2 min read
Dart Interfaces: Extending vs Implementing | Difference between Extends & Implements keyword

1. Extending (Extends keyword)

  • 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 class Dog that extends Animal, you're saying that Dog is a specific type of Animal.

  • 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');
        }
      }
    

    In this example, Dog extends Animal, indicating that a Dog is a specific type of Animal and inherits the eat() method.


2. Implementing (implements keyword)

  • 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');
        }
      }
    

    In this example, the Bird class implements the Flyable interface, which means that it agrees to provide an implementation for the fly() method defined in the Flyable interface.

    • In summary, extending is used for inheritance, where a subclass inherits properties and methods from a superclass, while implementing is used to fulfill a contract defined by an interface, providing specific behavior as required by that interface.

Dart

Part 29 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart Interfaces: Coding an Interface in Dart

In Dart, interfaces are not explicitly declared like in some other languages. Instead, you define an interface by creating an abstract class with abstract methods. Let's see how we can code an interface in Dart using an example: // Define an interfac...

More from this blog

Flutter Journey with Jinali

141 posts