객체의 인스턴스 메서드(Instance methods)는 인스턴스 변수 및 this에 접근할 수 있습니다. 아래 코드에서 distanceTo() 메서드는 인스턴스 메서드의 예입니다.
import 'dart:math';
class Point {
double x = 0;
double y = 0;
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);
}
}
연산자
연산자(Operators)는 특별한 이름을 갖는 인스턴스 메서드입니다. Dart에서는 아래 이름으로 연산자를 정의할 수 있습니다.
<
+
|
>>>
>
/
^
[]
<=
~/
&
[]=
>=
*
<<
~
-
%
>>
==
연산자 ==만 존재하고 !=는 존재하지 않는 것을 볼 수 있는데, !=은 syntactic sugar이기 때문입니다. 예를 들어, e1 != e2는 !(e1 == e2)의 syntactic sugar입니다.
연산자는 operator 식별자를 이용해 선언합니다. 아래 코드는 벡터의 더하기(+), 빼기(-)를 정의합니다.
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);
bool operator ==(other) =>
other is Vector &&
x == other.x &&
y == other.y;
int get hashCode => "$x,$y".hashCode;
}
void main() {
final v = Vector(2, 3);
final w = Vector(2, 2);
print("v + w == Vector(4, 5) ? ${v + w == Vector(4, 5)}");
print("v - w == Vector(0, 1) ? ${v - w == Vector(0, 1)}");
}
Getter와 Setter
Getter와 Setter는 객체의 속성에 대한 읽기와 쓰기 접근을 제공하는 특수한 메서드입니다. 각 인스턴스 변수에는 암시적 getter와 적절한 경우 setter가 존재합니다. get과 set 키워드를 사용하여 getter 및 setter를 구현하는 방법으로 추가 속성을 만들 수 있습니다.
아래 코드는 두개의 연산된 속성 right과 bottom을 정의합니다.
class Rectangle {
double left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
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);
print("rect.left == 3 ? ${rect.left == 3}");
rect.right = 12;
print("rect.left == -8 ? ${rect.left == -8}");
}
Getter와 setter를 사용하면 클라이언트 코드를 변경하지 않고 인스턴스 변수로 시작하여 후에 메서드로 변경할 수 있습니다.
double get right => left + width;
// 위와 동일한 코드
double get right {
return left + width;
}
추상 메서드
인스턴스 메서드와 getter, setter는 추상 메서드(Abstract methods)로 선언하여 인터페이스로 정의할 수 있습니다. 추상 메서드는 추상 클래스에만 존재할 수 있으며, 추상 클래스를 상속하는 쪽에서는 반드시 추상 메서드를 구현해야합니다. 추상 메서드로 선언하려면 메서드 바디 없이 ;를 사용하면 됩니다.
abstract class Doer {
void doSomething();
String get name;
}
class EffectiveDoer extends Doer {
void doSomething() {
// ...
}
String get name => "";
}