How to define interfaces in Dart?

前端 未结 4 1653
耶瑟儿~
耶瑟儿~ 2021-02-01 12:52

In Java, I might have an interface IsSilly and one or more concrete types that implement it:

public interfa         


        
相关标签:
4条回答
  • 2021-02-01 12:54

    In Dart, every class defines an implicit interface. You can use an abstract class to define an interface that cannot be instantiated:

    abstract class IsSilly {
        void makePeopleLaugh();
    }
    
    class Clown implements IsSilly {
    
        void makePeopleLaugh() {
            // Here is where the magic happens
        }
    
    }
    
    class Comedian implements IsSilly {
    
        void makePeopleLaugh() {
            // Here is where the magic happens
        }
    
    }
    
    0 讨论(0)
  • 2021-02-01 13:04

    In Dart there is a concept of implicit interfaces.

    Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

    A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces.

    So your example can be translate in Dart like this :

    abstract class IsSilly {
      void makePeopleLaugh();
    }
    
    class Clown implements IsSilly {
      void makePeopleLaugh() {
        // Here is where the magic happens
      }
    }
    
    class Comedian implements IsSilly {
      void makePeopleLaugh() {
        // Here is where the magic happens
      }
    }
    
    0 讨论(0)
  • 2021-02-01 13:05
    
    abstract class ORMInterface {
      void fromJson(Map<String, dynamic> _map);
    }
    
    abstract class ORM implements ORMInterface {
    
      String collection = 'default';
    
      first(Map<String, dynamic> _map2) {
        print("Col $collection");
      }
    }
    
    class Person extends ORM {
    
      String collection = 'persons';
    
      fromJson(Map<String, dynamic> _map) {
        print("Here is mandatory");
      }
    }
    
    
    0 讨论(0)
  • 2021-02-01 13:14

    The confusion usually is because doesn't exist the word "interface" like java and another languages. Class declarations are themselves interfaces in Dart.

    In Dart every class defines an implicit interface like others says.So then... the key is: Classes should use the implements keyword to be able to use an interface.

    abstract class IsSilly {
      void makePeopleLaugh();
    }
    
    //Abstract class
    class Clown extends IsSilly {   
      void makePeopleLaugh() {
        // Here is where the magic happens
      }
    }
    
    //Interface
    class Comedian implements IsSilly {
      void makePeopleLaugh() {
        // Here is where the magic happens
      }
    }
    
    0 讨论(0)
提交回复
热议问题