Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define interfaces in Dart?

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

public interface IsSilly {     public void makePeopleLaugh(); }  public class Clown implements IsSilly {     @Override     public void makePeopleLaugh() {         // Here is where the magic happens     } }  public class Comedian implements IsSilly {     @Override     public void makePeopleLaugh() {         // Here is where the magic happens     } } 

What's the equivalent to this code in Dart?

After perusing the official docs on classes, it doesn't seem that Dart has a native interface type. So, how does the average Dartisan accomplish the interface segregation principle?

like image 979
IAmYourFaja Avatar asked Dec 26 '13 21:12

IAmYourFaja


People also ask

Is there interface in Dart?

Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

Does Dart have multiple interfaces?

Dart does not support multiple inheritance but dart can implement multiple interfaces. To provide similar power and functionality.

What is implicit interface in Dart?

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.

What is difference between abstract and interface in Dart?

As such, abstract classes are used to define methods and properties without including implementation details. These methods, properties and other details make up the interface of the Class. Dart makes use of these class interfaces to create a description of the complex relationships between classes.


1 Answers

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   } } 
like image 106
Alexandre Ardhuin Avatar answered Sep 19 '22 01:09

Alexandre Ardhuin