Interfaces

  1. Interfaces
  2. An interface defines the same as the class where any set of methods can be accessed by an object. The class declaration can interface itself.

    We need to use implements keyword followed by class name to be able to use the interface.

    Syntax :

    class class_name implements interface_name

  3. Rules for Implementing Interfaces
    1. The class that implements interface must implement all the methods of that interface.

    2. The class declaration can be considered as the interface itself because dart doesn't provide syntax to declare the interface directly.

    3. An interface class must provide the full implementation of all the methods belong to the interfaces.

    4. We can implement one or more interfaces at the same time.


  4. Example 1 :

  5. class A {

      void printMyOrder() {

        print("My order is 1");

      }

     

      void printMyLowerCase() {

        print("My lower case is a");

      }

    }

     

    class D implements A {

      void printMyOrder() {

        print("My order is 4");

      }

     

      void printMyLowerCase() {

        print("My lower case is d");

      }

    }

     

    void main() {

      var a1 = A(), d1 = D();

      a1.printMyOrder();

      a1.printMyLowerCase();

      print("-----");

      d1.printMyOrder();

      d1.printMyLowerCase();

    }



    My order is 1
    My lower case is a
    -----
    My order is 4
    My lower case is d

  6. Example 2 :

  7. class Singer {

      void sing() {

        print("I am singing");

      }

    }

     

    class Dancer {

      void dance() {

        print("I am dancing");

      }

    }

     

    class Performer implements SingerDancer {

      void sing() {

        print("I am singing Unstoppable");

      }

     

      void dance() {

        print("I am dancing on the stage");

      }

    }

     

    void main() {

      var s = Singer(), d = Dancer(), p = Performer();

      s.sing();

      print("------");

      d.dance();

      print("------");

      p.sing();

      p.dance();

    }



    I am singing
    ------
    I am dancing
    ------
    I am singing Unstoppable
    I am dancing on the stage