[Flutter / Dart] 객체지향 프로그래밍(스태틱과 캐스케이드 연산자)
2025. 4. 8. 01:00
1. 스태틱
지금까지 작성한 변수와 메서드 등 모든 속성은 각 "클래스의 인스턴스"에 귀속됐었음.
하지만, `stataic`키워드를 사용하면 클래스 자체에 귀속됨.
class Counter {
// 1. static키워드를 사용해서 static 변수 선언
static int i = 0;
// 2. static 키워드를 사용해서 static 변수 선언
Counter() {
i++;
print(i++);
}
}
void main() {
Counter count1 = Counter();
Counter count2 = Counter();
Counter count3 = Counter();
}
/* 출력값
1
3
5
*/
- 변수 `i`를 `static`으로 지정했음
-> 스태틱 변수 (또는 정적 변수)라고 부름 - `Counter` 클래스에 귀속되기 때문에, 인스턴스를 새로 만들 때마다 공용 변수인 `i`가 1씩 증가
- 생성자에 `this.i`가 아니라 `i`로 명시함.
-> `static`변수는 클래스에 직접 귀속되기 때문에, `this.i`처럼 인스턴스가 가진 값으로 접근할 수 없음 - `this.i`는 인스턴스 변수일 떄 사용하는 방식, `static`변수는 클래스 자체에 속하므로 `this`로 접근하지 않음.
-> 클래스 이름으로 접근하는게 원칙 : `Counter.i` - 결론 : `static`키워드는 인스턴스끼리 공유해야 하는 정보에 지정하면 됨.
2. 캐스케이드 연산자
- 캐스케이드 연산자는 인스턴스에서 해당 인스턴스의 속성이나 멤버 함수를 연속해서 사용하는 기능임.
- `..`기호를 사용
상속에서 사용한 `Idol`클래스를 가져와서 사용해보겠음
// 캐스케이드 연산자
class Idol {
final String name;
final int membersCount;
Idol(this.name, this.membersCount);
void sayName() {
print("저는 ${this.name}입니다.");
}
void sayMembersCount() {
print("${this.name}멤버는 ${this.membersCount}명입니다.");
}
}
void main() {
// cascade operator (..)을 사용하면 선언한 변수의 메서드를 연속해서 실행 가능
Idol blackPink = Idol("블랙핑크", 4)
..sayName()
..sayMembersCount();
}
/* 출력값
저는 블랙핑크입니다.
블랙핑크 멤버는 4명입니다.
*/
이처럼 캐스케이드 연산자를 사용하면 더 간결한 코드를 작성할 수 있음. 아래에 기존 코드를 보면서 비교해보면 됨
// 부모 클래스
class Idol {
final String name;
final int membersCount;
Idol(this.name, this.membersCount);
void sayName() {
print("저는 ${this.name}입니다.");
}
void sayMembersCount() {
print("${this.name}멤버는 ${this.membersCount}명입니다.");
}
}
// 자식 클래스
class GirlGroup extends Idol {
GirlGroup(
String name,
int membersCount,
) : super(
name,
membersCount,
);
void sayFeMale() {
print("저는 여자 아이돌입니다.");
}
}
void main() {
GirlGroup blackPink = GirlGroup("블랙핑크", 4);
blackPink.sayName();
blackPink.sayMembersCount();
}
확실히 코드의 길이가 간결해진 것을 볼 수 있음
https://github.com/Leedoseo/Flutter_OOP_basic
GitHub - Leedoseo/Flutter_OOP_basic
Contribute to Leedoseo/Flutter_OOP_basic development by creating an account on GitHub.
github.com
https://www.notion.so/Dart-Flutter-Study-1cf9fd9f157980a5ab7efad394810871?pvs=4
Dart / Flutter Study | Notion
Made with Notion, the all-in-one connected workspace with publishing capabilities.
www.notion.so
출처 : 코드팩토리의 플러터 프로그래밍
'Dart 언어' 카테고리의 다른 글
[Flutter / Dart] 다트 3.0 신규 문법 (레코드) (0) | 2025.04.11 |
---|---|
[Flutter / Dart] 비동기 프로그래밍 (0) | 2025.04.09 |
[Flutter / Dart] 객체지향 프로그래밍(추상과 제네릭) (0) | 2025.04.08 |
[Flutter / Dart] 객체지향 프로그래밍(인터페이스와 믹스인) (1) | 2025.04.07 |
[Flutter / Dart] 객체지향 프로그래밍(상속과 오버라이드) (0) | 2025.04.07 |