Dart ๋ฌธ๋ฒ ๊ธฐ์ด - 2
class & object
- Object : ๋ฐ์ดํฐ ํน์ ๊ธฐ๋ฅ์ด ์ ์๋์ด ์์ผ๋ฉฐ ํ๋ก๊ทธ๋จ ์์์ ๋ค๋ฃฐ ์ ์๋ ๊ฐ์ฒด
- Class: Object ์ ๋ฐ์ดํฐ์ ๊ธฐ๋ฅ์ด ์ ์๋์ด ์๋ ์ค๊ณ๋
- Class์ ๊ตฌ์ฑ์์
- ์ฌ์ฉ ๋ฐฉ๋ฒ
class Person{
String name;
int age;
Person(this.name, this.age);
void printInfo(){
print('${name} is ${age} years old.');
}
}
void main() {
var person = Person('John Doe', 30);
person.printInfo();
var person2 = Person('Sanghyun Ha', 28);
person2.printInfo();
}
Inheritance

- ์ธ์ง ํด์ผ ํ ํค์๋:
extends, super, @override
- ๋ถ๋ชจ ํด๋์ค : IronMan
class IronMan {
String name;
int powerLevel;
IronMan(this.name, this.powerLevel);
void shoot() {
print('$name is shooting guns!');
}
}
- ์์ ํด๋์ค: IronManMK3
class IronManMK3 extends IronMan {
int flyHeight;
IronManMK3(String name, int powerLevel, this.flyHeight)
: super(name, powerLevel);
@override
void shoot() {
-> print('$name is shooting Laser!');
}
void fly() {
print('$name is Flying!');
}
}
void main() {
IronMan mk1 = IronMan("mk1", 10);
IronManMK3 mk3 = IronManMK3("mk3", 20, 1000);
mk1.shoot();
mk3.shoot();
}
abstract class
- Dart class๋ ์์์ ์ผ๋ก ์ธํฐํ์ด์ค์ ์ญํ ์ ํ ์ ์์ต๋๋ค.
- Abstract์ ์ธํฐํ์ด์ค๋ ์ญํ ์ด ์ด๋ ์ ๋ ๊ฒน์น๊ธฐ ๋๋ฌธ์ Abstract ํค์๋๋ฅผ ์ฌ์ฉํด ์ํ๋ ๋ฉ์๋๋ฅผ ๊ตฌํํ๋๋ก ํ ์ ์์ต๋๋ค.
- abstract class
abstract class IronMan {
late String name;
late String suitColor;
void fly();
void shootLasers();
void withstandDamage();
}
- abstract class ์ฌ์ฉ ๋ฐฉ๋ฒ
class Mark50 extends IronMan {
Mark50(String name, String suitColor) {
this.name = name;
this.suitColor = suitColor;
}
@override
void fly() {
print('${this.name} is flying!');
}
@override
void shootLasers() {
print('${this.name} is shooting lasers!');
}
@override
void withstandDamage() {
print('${this.name} is withstanding damage!');
}
}
void main(){
var markSeeun = Mark50('์ธ์', '๋ ๋');
markSeeun.fly();
}
mixin
- Dart๋ Mixin์ ํตํด class์ ๊ธฐ๋ฅ์ ์ถ๊ฐํ ์ ์์ต๋๋ค.
- ํด๋์ค๋ ์์๋ ๋ฐ๊ณ , mixin๋ ๋ฐ๋๋ค.
- mixin
mixin Flyable on Animal {
void fly() {
print('I am flying!');
}
}
class Animal {
String name;
Animal(this.name);
}
- ํด๋์ค + ์์ ํด๋์ค + mixin
class Bird extends Animal with Flyable {
Bird(String name) : super(name);
}
void main() {
var bird = Bird('Bird');
bird.fly();
}