メソッド
メソッドは、オブジェクトに振る舞いを提供する関数です。
インスタンスメソッド
#オブジェクトのインスタンスメソッドは、インスタンス変数とthisにアクセスできます。以下のサンプルコードのdistanceTo()メソッドは、インスタンスメソッドの例です。
dart
import 'dart:math';
class Point {
final double x;
final double y;
// Sets the x and y instance variables
// before the constructor body runs.
Point(this.x, this.y);
double distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
}演算子
#ほとんどの演算子は、特別な名前を持つインスタンスメソッドです。Dartでは、以下の名前で演算子を定義できます。
< | > | <= | >= | == | ~ |
- | + | / | ~/ | * | % |
| | ˆ | & | << | >>> | >> |
[]= | [] |
演算子を宣言するには、組み込み識別子operatorの後に、定義する演算子を使用します。次の例では、ベクトル加算(+)、減算(-)、および等価性(==)を定義しています。
dart
class Vector {
final int x, y;
Vector(this.x, this.y);
Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
@override
bool operator ==(Object other) =>
other is Vector && x == other.x && y == other.y;
@override
int get hashCode => Object.hash(x, y);
}
void main() {
final v = Vector(2, 3);
final w = Vector(2, 2);
assert(v + w == Vector(4, 5));
assert(v - w == Vector(0, 1));
}ゲッターとセッター
#ゲッターとセッターは、オブジェクトのプロパティへの読み書きアクセスを提供する特別なメソッドです。各インスタンス変数には、暗黙的なゲッターがあり、適切であればセッターもあります。getおよびsetキーワードを使用して、ゲッターとセッターを実装することで、追加のプロパティを作成できます。
dart
class Rectangle {
double left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
// Define two calculated properties: right and bottom.
double get right => left + width;
set right(double value) => left = value - width;
double get bottom => top + height;
set bottom(double value) => top = value - height;
}
void main() {
var rect = Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
}ゲッターとセッターを使用すると、インスタンス変数から始め、後でメソッドでラップすることができます。これらすべて、クライアントコードを変更することなく行うことができます。
抽象メソッド
#インスタンスメソッド、ゲッター、セッターは抽象にでき、インターフェイスを定義しながら、その実装を他のクラスに任せます。抽象メソッドは、抽象クラスまたはミックスインにのみ存在できます。
メソッドを抽象にするには、メソッド本体の代わりにセミコロン(;)を使用します。
dart
abstract class Doer {
// Define instance variables and methods...
void doSomething(); // Define an abstract method.
}
class EffectiveDoer extends Doer {
void doSomething() {
// Provide an implementation, so the method is not abstract here...
}
}