Class(ํด๋์ค)
์ด๋ฒ์ Class ๋ค. Object Oriented Programming, ํต์นญ OOP ๋ผ๋ ๊ฐ์ฒด์งํฅํ๋ก๊ทธ๋๋ฐ์ ๋ค์ด๋ณธ ์ฌ๋์ด๋ผ๋ฉด ํ ๋ฒ์ฏค์ ๋ค์ด๋ดค์ class๋ ์์ฑ์(constructor), ๋ฉ์๋(๋ด๋ถ ํจ์ - method), ๊ฐ์ฒด ๋ฑ์ ํค์๋๋ก ๊ฐ๋ ์ด ์ด๋ฃจ์ด์ ธ ์๋ค. Dart ์ class๋ C++์ ์ธ๋ป ๋น์ทํ ํํ๋ก์จ ์ธ์ด์ ์ธก๋ฉด์์ ์ฝ๊ฐ์ ์ฐจ์ด๊ฐ ์๋ค.
๋ค์์ Dart.dev์ ๊ณต์ ์ฌ์ดํธ์์ ๋ค๊ณ ์จ ์์๋ค. ๋น๊ต๋ฅผ ํตํด ํ ๋ฒ ์ดํด๋ณด์.
class Spacecraft {
String name;
DateTime? launchDate;
// Read-only non-final property
int? get launchYear => launchDate?.year;
/*
launchYear ๋ผ๋ ์ด๋ฆ์ getter ํจ์๋ฅผ ์ ์ธํ๋ ๊ฑธ ์๋ฏธ.
? launchDate?.year : launchDate๊ฐ null์ด ์๋ ๊ฒฝ์ฐ launchDate์ ๋ฉค๋ฒ์ธ year ๊ฐ์ ์ถ์ถํจ.
*/
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) { // this ๋ฌธ๋ฒ. ์
๋ ฅ ๋ฐ์ ๋๊ฐ์ ํ๋ผ๋ฉํ๋ฅผ ๊ฐ์ฒด ์์ ์ ๋ฉค๋ฒ ๋ณ์์ ๊ฐ๊ฐ ๋์ํ๋ ๊ฒ์ผ๋ก ๋์
// Initialization code goes here.
}
/*
Class aggregation์ ์ํ 2์ 3๋ฒ ๋ผ์ธ๋ ๋์ผ.
Dart์ ํด๋์ค๋ C++๊ณผ ๋์ผํ๊ฒ constructor๋ฅผ ๊ฐ์ง๋ฉฐ, C++๊ณผ ์ ์ฌํ ๋ฐฉ์.
์
๋ ฅ ํ๋ผ๋ฉํ ๋ถ๋ถ์์ this์ ‘.’ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉ.
*/
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
/*
์์ฑ์ (ํจ์ ์ด๋ฆ) : unlaunched
์
๋ ฅ ํ๋ผ๋ฏธํฐ(String name : 1๊ฐ) -> ๋ฉค๋ฒ ๋ณ์ : name์ ์ฑ์, launchDate = null
*/
// Method.
void describe() { // return ๊ฐ : ์์. ์
๋ ฅ ๊ฐ : ์์.
print('Spacecraft: $name'); // class ์ด๋ฆ๊ณผ ๊ฐ์ฒด ์ด๋ฆ์ ์ถ๋ ฅ. $ ๊ธฐํธ : ํด๋น ๊ธฐํธ ๋ค์ ๋ณ์ ์ด๋ฆ์ ์ถ๋ ฅ.
// Type promotion doesn't work on getters.
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365; // division operator, ์ ์ํ ๊ฒฐ๊ณผ๊ฐ์ return ํจ.
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
# Spacecraft class ์์. (์ถ์ฒ: Dart.dev)
Inheritance(์์)
Dart์ ์ ์ ์ ๋ฒ์น์ single inheritance๊ฐ ์์น์ด๋ค. ๋ค์์ base class๋ก๋ถํฐ ์ฌ๋ฌ ๊ฐ์ derived class ๋ฅผ ๋ง๋ค ์ ์๋ C++๊ณผ๋ ์ฐจ์ด๊ฐ ์๋ค. ์ฆ, ๋ณต์์ base class๋ฅผ ๊ฐ์ง ๋ชปํ๋๋ก ๊ถ๊ณ ํ๋ ์ต๊ทผ ์ธ์ด๋ค์ ํน์ง์ ๋๊ณ ์๋ค.
- C++ inheritance ๋ฐฉ์ : ' : '
- Dart inheritance ๋ฐฉ์ : 'extends'
class Orbiter extends Spacecraft {
num altitude; //derived class์๋ ์๋ก์ด ๋ฉค๋ฒ ๋ณ์ : altitude, num ํ์
๊ฐ์ฒด
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
/*
ํด๋์ค ์ด๋ฆ๊ณผ ๊ฐ์ ์ด๋ฆ์ constructor.
3๊ฐ์ ์
๋ ฅ ํ๋ผ๋ฉํ๋ฅผ ๋ฐ์ผ๋ฉด, name๊ณผ launchDate๋
base class ๋ด๋ถ์ ๋ฉค๋ฒ ๋ณ์๋ก ์ ๋ฌ.
์๋กญ๊ฒ ๋ง๋ค์ด์ง altitude ๋ณ์๋ฅผ ์ธ ๋ฒ์งธ ์
๋ ฅ ํ๋ผ๋ฉํ ๊ฐ์ผ๋ก ์ ์ฅ.
*/
}
์ด๋ฒ ๊ธ๊น์ง๋ C++์ Dart์ ์ฐจ์ด์ /๊ณตํต์ ์ ํ์ ํ๋ ๋ด์ฉ์ด ์ฃผ์๋ค๋ฉด, Dart ์ธ์ด์ ์์ธํ ๋ฌธ๋ฒ์ ๋ด์ฉ๋ค์ ์ถํ ํฌ์คํธ์์ ์ง์์ ์ผ๋ก ์ ๋ฐ์ดํธ ํ ์์ !
C++์ ๋ฌธ๋ฒ๋ ์ถ๊ฐ์ ์ผ๋ก ๊ณต๋ถํ๋ฉด์ ๋ณต์ตํด์ผ๊ฒ ๋ค.. ์ ๊ธฐ์ต์ด ๋์ง ์๋ ๋ถ๋ถ๋ ์๋ ๋งํผ ์ ๋ฐ์ดํธ ํ๋ฉด์ ๋ด์ฉ๋ ์ถ๊ฐ๋ก ๋ณด์ถฉํ ์์ !
'Dart, Flutter > ๐ณ Basic' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Dart [์ซ์ํ, ๋ฌธ์ํ, Boolean Types] (0) | 2024.01.18 |
---|---|
Dart [๋ณ์ & ์์] (0) | 2023.12.23 |
Dart [Hello World!] (0) | 2023.12.21 |
[Dart vs C++] ver1 (1) | 2023.12.18 |
Dart ์์ํ๊ธฐ [์ค์น ํธ] (2) | 2023.12.18 |