728x90

✅ 1. Dart 클래스 (Class)
Dart의 Class는 객체를 만들기 위한 설계도로 틀과 같습니다. 클래스는 변수(필드)와 함수(메서드)를 묶어 정의합니다. Dart에서는 class 키워드로 선언합니다.
class Person {
String name;
int age;
// Constructor 생성자
Person(this.name, this.age);
// Name constructor 이름 생성자
Person.guest() : name = "Guest", age = 0;
// Method 메소드
void introduce() {
print('Hello, my name is $name and I am $age years old.');
}
}
✅ 2. 객체 (Object)
객체는 클래스를 기반으로 만든 실제 데이터 덩어리이며 클래스에서 정의한 속성과 기능을 가집니다. 객체를 생성 시 new 키워드는 생략이 가능합니다.
void main() {
var p = Person("Alice", 30);
p.introduce(); // Hello, my name is Alice and I am 30 years old.
var g = Person.guest();
g.introduce(); // Hello, my name is Guest and I am 0 years old.
}
✅ 3. 생성자 종류
Dart에는 다양한 생성자 종류가 있습니다. 다음은 생성자 종류에 대한 코드입니다.
class Sword {
String name;
int damage;
// 기본 생성자
Sword(this.name, this.damage);
// 이름 있는 생성자
Sword.magic(this.name) : damage = 100;
// 메소드
void attack() {
print('Attacking with $name for $damage damage!');
}
}
void main() {
var sword1 = Sword("King's Sword", 50);
var sword2 = Sword.magic('Magic Sword');
sword1.attack(); // Attacking with King's Sword for 50 damage!
sword2.attack(); // Attacking with Magic Sword for 100 damage!
}
✅ 4. 클래스 특징
- 모든 것이 객체 -> 숫자, 문자열, 함수도 객체
- this 키워드로 현재 객체 참조 가능
- private 필드/메서드는 언더스코어( _ ) 로 시작
- 클래스는 상속, 추상화, mixin 모두 지원
✅ 5. 상속 예제
class Nintendo {
void play() {
print("Playing Nintendo games!");
}
}
class Mario extends Nintendo {
@override
void play() {
print("Playing Mario games!");
}
}
void main() {
var mainCharcter = Mario();
mainCharcter.play();
var nintendo = Nintendo();
nintendo.play(); // Output: Playing Nintendo games!
}
GitHub - Koras02/dart-bloging
Contribute to Koras02/dart-bloging development by creating an account on GitHub.
github.com
728x90
LIST
'Mobile > Dart' 카테고리의 다른 글
| [Dart] 12장 상속 (1) | 2025.08.17 |
|---|---|
| [Dart] 11장 생성자와 초기화 리스트 (3) | 2025.08.11 |
| [Dart] 9장 화살표 함수 (0) | 2025.08.05 |
| [Dart] 8장 익명 함수 및 고차 함수 (0) | 2025.03.31 |
| [Dart] 7장 매개변수와 반환값 (0) | 2025.03.25 |