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
Greeterclass implements the Core Library'sComparableinterface, making it easy to compare twoGreeterobjects. Implementing the interface consists of two steps: addingimplements Comparableto theclassstatement (line 1), and adding a definition of the only method required byComparable:compareTo()(line 7). -
intandnuminterfaces -
Although you might expect
intanddoubleto be primitive types, they're actually interfaces that extend thenuminterface. This means thatintanddoublevariables are alsonums.In use,
intanddoublefeel 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.
