Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 신재생에너지 발전설비 기사
- jpa
- 시스템
- write by GPT-4
- Java
- python
- 인프라
- write by chatGPT
- spring integration
- kotlin
- 파이썬
- 고전역학
- flet
- spring data jpa
- chatGPT's answer
- flutter
- 유닉스
- 역학
- 소프트웨어공학
- NIO
- Database
- 자바
- GPT-4's answer
- mobile programming
- 자바네트워크
- oracle
- 코틀린
- DART
- 리눅스
- 데이터베이스
Archives
- Today
- Total
기억을 지배하는 기록
Dart 객체지향 프로그래밍 - 클래스와 객체 본문
728x90
Dart 객체지향 프로그래밍 (OOP) - Class와 Object
Dart는 객체지향 프로그래밍(OOP: Object-Oriented Programming)을 지원하는 언어입니다.
OOP의 핵심 개념인 클래스(Class), 객체(Object), 생성자(Constructor), 상속(Inheritance), 다형성(Polymorphism), 캡슐화(Encapsulation), 추상 클래스(Abstract Class), 인터페이스(Interface), 믹스인(Mixin) 등을 지원합니다.
1. 클래스(Class)와 객체(Object)
Dart에서 클래스는 객체를 생성하는 틀(템플릿) 역할을 하며, 객체는 클래스의 인스턴스(Instance) 입니다.
1. 1 클래스 정의 및 객체 생성
class Person {
String name = "Unknown";
int age = 0;
void introduce() {
print("안녕하세요, 제 이름은 $name이고, 나이는 $age살입니다.");
}
}
void main() {
Person p1 = Person(); // 객체 생성
p1.name = "Alice";
p1.age = 25;
p1.introduce();
}
안녕하세요, 제 이름은 Alice이고, 나이는 25살입니다.
- Person 클래스에서 name, age와 같은 속성(멤버 변수)과 introduce() 같은 메서드를 정의합니다.
1. 2 생성자(Constructor)
생성자는 객체가 생성될 때 자동으로 실행되는 함수입니다.
1.2.1 기본 생성자
class Person {
String name;
int age;
// 기본 생성자
Person(String name, int age) {
this.name = name;
this.age = age;
}
void introduce() {
print("이름: $name, 나이: $age");
}
}
void main() {
Person p = Person("Bob", 30);
p.introduce(); // 이름: Bob, 나이: 30
}
1.2.2 간결한 생성자 (this 사용)
class Person {
String name;
int age;
// 간결한 생성자
Person(this.name, this.age);
}
void main() {
Person p = Person("Charlie", 40);
print(p.name); // Charlie
}
- this.name = name;을 this.name, this.age 형태로 간결하게 작성할 수 있습니다.
1.2.3 네임드 생성자 (Named Constructor)
클래스에는 여러 개의 생성자를 정의할 수 있습니다.
class Person {
String name;
int age;
Person(this.name, this.age);
// 네임드 생성자
Person.withoutAge(this.name) {
age = 0;
}
void introduce() {
print("이름: $name, 나이: $age");
}
}
void main() {
Person p1 = Person("Alice", 25);
Person p2 = Person.withoutAge("Bob");
p1.introduce(); // 이름: Alice, 나이: 25
p2.introduce(); // 이름: Bob, 나이: 0
}
- Person.withoutAge("Bob")처럼 특정 생성자를 호출할 수 있습니다.
1.2.4 리디렉팅 생성자 (Redirecting Constructor)
리디렉팅 생성자는 기존 생성자를 호출하여 중복 코드 작성을 방지할 수 있습니다.
class Person {
String name;
int age;
// 기본 생성자
Person(this.name, this.age);
// 리디렉팅 생성자 1
Person.withDefaultAge(String name) : this(name, 20);
// 리디렉팅 생성자 2
Person.empty() : this("Unknown", 0);
void introduce() {
print("이름: $name, 나이: $age");
}
}
void main() {
Person p1 = Person("David", 30);
Person p2 = Person.withDefaultAge("Eve");
Person p3 = Person.empty();
p1.introduce(); // 이름: David, 나이: 30
p2.introduce(); // 이름: Eve, 나이: 20
p3.introduce(); // 이름: Unknown, 나이: 0
}
이름: David, 나이: 30
이름: Eve, 나이: 20
이름: Unknown, 나이: 0
- Person.withDefaultAge 생성자는 기본 생성자 Person(this.name, this.age)를 호출하여 age를 20으로 설정.
- Person.empty 생성자도 기본 생성자로 전달하여 name을 "Unknown", age를 0으로 설정.
1.2.5 초기화 리스트 (Initializer List)
Dart에서는 초기화 리스트(Initializer List) 를 사용하여 생성자 실행 전에 필드를 초기화할 수 있습니다.
class Person {
final String name;
final int age;
// 초기화 리스트 사용
Person(this.name, this.age) : assert(age >= 0, "나이는 음수가 될 수 없습니다.");
void introduce() {
print("이름: $name, 나이: $age");
}
}
void main() {
Person p1 = Person("Frank", 25);
// Person p2 = Person("Grace", -5); // ❌ 오류 발생 (assert 체크)
p1.introduce(); // 이름: Frank, 나이: 25
}
- assert를 사용하여 잘못된 값이 들어오는 것을 방지 가능.
- 필드가 final인 경우 반드시 초기화해야 함.
1.2.6. 팩토리 생성자 (Factory Constructor)
factory 생성자는 새로운 인스턴스를 반환하거나, 기존 객체를 반환하는 생성자입니다.
class Person {
String name;
int age;
// private 생성자 (외부에서 직접 접근 불가능)
Person._internal(this.name, this.age);
// factory 생성자
factory Person(String name, int age) {
if (age < 0) {
return Person._internal(name, 0); // 나이가 음수면 0으로 설정
}
return Person._internal(name, age);
}
void introduce() {
print("이름: $name, 나이: $age");
}
}
void main() {
Person p1 = Person("Henry", 30);
Person p2 = Person("Ivy", -5);
p1.introduce(); // 이름: Henry, 나이: 30
p2.introduce(); // 이름: Ivy, 나이: 0
}
- 객체를 직접 생성하지 않고, 조건에 따라 특정 인스턴스를 반환 가능.
- Person._internal → private 생성자 사용.
1.3. 생성자 방법 비교
생성자 유형 | 설명 | 예시 |
기본 생성자 | 클래스에 가장 기본적으로 존재하는 생성자 | Person(this.name, this.age); |
네임드 생성자 | 여러 개의 생성자를 정의할 때 사용 | Person.withDefaultAge(this.name); |
리디렉팅 생성자 | 다른 생성자로 위임 (중복 코드 방지) | Person.withDefaultAge(String name) : this(name, 20); |
초기화 리스트 | 생성자 실행 전에 필드 초기화 | Person(this.name, this.age) : assert(age >= 0); |
팩토리 생성자 | 기존 객체를 반환하거나, 새로운 인스턴스를 반환 | factory Person(String name, int age) {...} |
728x90
'Flutter for Beginners' 카테고리의 다른 글
Dart 객체지향 프로그래밍 - 상속(Inheritance) (0) | 2025.02.24 |
---|---|
Dart 화살표 함수 (0) | 2025.02.21 |
Dart의 예외 처리 (0) | 2025.02.21 |
Dart의 함수(Function)와 람다(Lambda) (0) | 2025.02.21 |
Dart의 제어문 (0) | 2025.02.20 |
Comments