Dart, 클래스 변수와 메서드
글. 수알치 오상문
static 키워드를 사용하여 클래스 범위의 변수 및 메서드를 만들 수 있습니다.
static 변수
static 변수(클래스 변수)는 클래스 범위의 상태와 상수에 유용합니다. static 변수는 사용될 때까지 초기화되지 않습니다.
class Queue {
static const initialCapacity = 16;
// ···
}
void main() {
assert(Queue.initialCapacity == 16);
}
static 메서드
static 메서드(클래스 메서드)는 인스턴스에서 작동하지 않지만 static 변수에 접근할 수 있습니다. 다음 예제는 클래스에서 직접 static 메서드를 호출합니다.
import 'dart:math';
class Point {
double x, y;
Point(this.x, this.y);
static double distanceBetween(Point a, Point b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
}
void main() {
var a = Point(2, 2);
var b = Point(4, 4);
var distance = Point.distanceBetween(a, b);
assert(2.8 < distance && distance < 2.9);
print(distance);
}
참고: 일반적이거나 널리 사용되는 유틸리티 및 기능은 static 메서드 대신에 최상위 수준 함수를 사용하는 것이 좋습니다.
static 메서드를 컴파일 시간에 상수로 사용할 수 있습니다. 예를 들어 static 메서드를 상수 생성자에 매개변수로 전달할 수 있습니다.
<이상>
'Dart' 카테고리의 다른 글
Dart, 라이브러리와 가시성 (0) | 2021.06.17 |
---|---|
Dart, 제너릭(Generic) (0) | 2021.06.17 |
Dart, 클래스에 기능 추가하기(mixin) (0) | 2021.06.17 |
Dart, 열거형 (Enumerated type) (0) | 2021.06.17 |
Dart, 클래스 class 확장 (0) | 2021.06.17 |