Tutorial: Interfaces

Interfaces—types that define which methods a class provides—are important in Dart. In fact, much of the Dart Core Library is defined in terms of interfaces. If you've never used a language that features interfaces or protocols, you might want to read about them.

class Greeter implements Comparable { String prefix = 'Hello,'; Greeter() {} Greeter.withPrefix(this.prefix); greet(String name) => print('$prefix $name'); int compareTo(Greeter other) => prefix.compareTo(other.prefix); } void main() { Greeter greeter = new Greeter(); Greeter greeter2 = new Greeter.withPrefix('Hi,'); num result = greeter2.compareTo(greeter); if (result == 0) { greeter2.greet('you are the same.'); } else { greeter2.greet('you are different.'); } }

About the code

The preceding code both uses and implements interfaces. Here's what's interesting about it:

Interface implementation
The Greeter class implements the Core Library's Comparable interface, making it easy to compare two Greeter objects. Implementing the interface consists of two steps: adding implements Comparable to the class statement (line 1), and adding a definition of the only method required by Comparable: compareTo() (line 7).
int and num interfaces
Although you might expect int and double to be primitive types, they're actually interfaces that extend the num interface. This means that int and double variables are also nums.

In use, int and double feel like the primitive types you're probably used to. For example, you can use literals to set their values:

int height = 160;
double rad = 0.0;

More about interfaces

In Dart, you can often create objects directly from an interface, instead of having to find a class that implements that interface. This is possible because many interfaces have a factory class—a class that creates objects that implement the interface. For example, if your code says new Date.now(), the factory class for the Date interface creates an object that represents the current time.

Next, you can either try out Dart Editor or read more about Dart.

Dart Editor Technical Overview