Dart Interfaces : Interfaces and the Dart SDK

Dart Interfaces : Interfaces and the Dart SDK

·

1 min read

Interfaces and the Dart SDK :

  • In Dart, interfaces provide a way to define a contract for classes to adhere to, without specifying how they should implement the contract. This allows for polymorphism and abstraction in Dart programs.

  • Here's a basic example of how interfaces work in Dart:

      // Define an interface
      abstract class Animal {
        void makeSound();
      }
    
      // Implement the interface
      class Dog implements Animal {
        @override
        void makeSound() {
          print('Woof!');
        }
      }
    
      class Cat implements Animal {
        @override
        void makeSound() {
          print('Meow!');
        }
      }
    
      void main() {
        // Create instances of classes that implement the interface
        Animal dog = Dog();
        Animal cat = Cat();
    
        // Call the method defined in the interface
        dog.makeSound(); // Output: Woof!
        cat.makeSound(); // Output: Meow!
      }