인스턴스 vs 정적 멤버
Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 110개 중 17번째.
Dart 클래스에서 멤버(변수 및 메서드)는 개별 객체에 속하거나 클래스 자체에 속할 수 있습니다. 이 차이를 이해하는 것은 코드를 효과적으로 구성하는 데 기본이 됩니다.
인스턴스 멤버는 사용자가 생성하는 각 객체에 속합니다. 모든 객체는 인스턴스 변수의 자체 복사본을 가지며, 인스턴스 메서드는 해당 객체의 데이터에 대해 작동합니다:
class Dog {
String name; // 인스턴스 변수
Dog(this.name);
void bark() { // 인스턴스 메서드
print('$name says woof!');
}
}
Dog dog1 = Dog('Buddy');
Dog dog2 = Dog('Max');
dog1.bark(); // Buddy says woof!
dog2.bark(); // Max says woof!각 Dog 객체는 고유한 name을 가집니다. 한 강아지의 이름을 변경해도 다른 강아지에는 영향을 주지 않습니다.
정적 멤버는 특정 객체가 아니라 class 자체에 속합니다. 정적 멤버는 모든 인스턴스에서 공유되며 class 이름을 사용하여 액세스합니다:
class Dog {
String name;
static int totalDogs = 0; // 정적 변수
Dog(this.name) {
totalDogs++;
}
}
Dog dog1 = Dog('Buddy');
Dog dog2 = Dog('Max');
print(Dog.totalDogs); // 2totalDogs 변수는 공유됩니다. Dog 객체가 몇 개 존재하든 사본은 하나뿐입니다. 인스턴스를 통해서가 아니라 클래스 이름 Dog.totalDogs를 통해 접근합니다.
챌린지
쉬움개별 전시 관람 횟수와 박물관 전체 통계를 모두 추적하는 박물관 방문자 카운터 시스템을 만들어 봅시다.
코드를 두 개의 파일로 구성합니다.
exhibit.dart: 박물관 전시물을 나타내는Exhibitclass를 정의합니다. 각 전시물에는 다음 항목이 있어야 합니다.- 전시물의 이름을 위한 instance variable
name(String) - 이 specific 전시물을 방문한 사람 수를 추적하기 위한
visitorCount(int) instance variable. 시작 값은0입니다. - 모든 전시물의 전체 방문 횟수를 추적하기 위한
totalVisitors(int) static variable. 시작 값은0입니다. - 전시물 이름을 받는 Constructor
- 전시물의
visitorCount와 class의totalVisitors를 모두 increments하는recordVisit()method - 전시물의 정보를 Prints하는
displayStats()method
- 전시물의 이름을 위한 instance variable
main.dart: exhibit class를 import하고 두 개의 전시물을 Create합니다.'Dinosaur Bones'전시물'Ancient Egypt'전시물
displayStats()를 Call하고, 모든 전시물의 total visitors를 Print합니다.
displayStats() method는 다음 exact format으로 Prints해야 합니다.
[name]: [visitorCount] visitorstotal visitors 줄에는 다음을 Print합니다.
Total museum visitors: [totalVisitors]static variable에는 class name Exhibit.totalVisitors를 사용해 Access합니다.
Expected output:
Dinosaur Bones: 3 visitors
Ancient Egypt: 2 visitors
Total museum visitors: 5직접 해보기
import 'exhibit.dart';
void main() {
// TODO: Create a 'Dinosaur Bones' exhibit
// TODO: Create an 'Ancient Egypt' exhibit
// TODO: Record 3 visits to the Dinosaur Bones exhibit
// TODO: Record 2 visits to the Ancient Egypt exhibit
// TODO: 각 exhibit에 순서대로 displayStats()를 호출하세요
// TODO: Print total museum visitors using Exhibit.totalVisitors
// Format: Total museum visitors: [totalVisitors]
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러