Dart
Dart - Class
zhilly
2024. 3. 11. 18:21
Named Constructors Parameter
class를 정의할 때에는 타입명시 해줘야한다.
class 내의 메서드에서 이름이 겹치지 않는 이상 this를 사용하는 것은 권장되지 않음.
상속은 extends로
생성자는 class의 이름과 똑같은 키워드로 만든다
class Player {
final String name;
int xp;
// 1번
Player(this.name, this.xp);
// 2번
Player(String name, int xp) {
this.name = name
this.xp = xp
}
void sayHello() {
print('my name is $name, xp is $xp');
}
}
기본적으로 기본값을 주지 않고 인스턴스 생성시에 값을 받으려면
required를 사용한다.
class Player {
final String name;
int xp;
Player({required this.name, required this.xp});
void sayHello() {
print('my name is $name, xp is $xp');
}
}
Named Constructors(Designed Initializer)
Player.createBluePlayer({
required String name,
required int age,
}) : this.age = age,
this.name = name,
this.team = 'blue',
this.xp = 0;
Cascade Notation
var player = Player(name: 'zhilly', xp: 100, team: 'iOS', age: 28)
..age = 19
..xp = 299
..team = 'blue';
.. 을 통해서 빠르게 접근할 수 있다.
Enum
enum Team {
red,
blue;
String get description {
switch (this) {
case red:
return '빨강팀';
case blue:
return '파란팀';
default:
return 'no descripiton';
}
}
}
Abstract Class (Protocol)
class Human {
final String name;
Human({required this.name});
void sayHello() {
print("Hi my name is $name");
}
}
class Player extends Human {
final Team team;
Player({
required this.team,
required String name,
}) : super(name: name);
@override
void sayHello() {
// TODO: implement sayHello
print('super\\'s sayhello');
super.sayHello();
print('hhiii ');
}
}
Mixins
- 생성자가 없는 클래스
- 클래스에 프로퍼티를 하나하나 추가할 때 사용한다.
- class 키워드 앞에 mixin 키워드를 사용한다.
- Mixin 클래스를 사용할 때에는 with 키워드를 사용한다.
- 여러 클래스에 재사용 가능하다.
mixin class Strong {
final double strenghtLevel = 1400.99;
}
// class 키워드 생략 가능
mixin classQuickRunner {
void runQuick() {
print('run~!!!!');
}
}
class Human with Strong, QuickRunner {
final String name;
Human({required this.name});
void sayHello() {
print("Hi my name is $name");
}
}