DART
[노마드코더 : Dart 시작하기] #4.1 Constructors
유호야
2022. 11. 19. 08:35
반응형
class Player {
late final String name;
late int xp;
Player(String name, int xp) {
this.name = name;
this.xp = xp;
}
void sayHello() {
print("Hi, my name is $name");
}
}
void main() {
var player = Player("Pau", 500);
player.sayHello();
}
class Player {
late final String name;
late int xp;
Player(this.name, this.xp);
void sayHello() {
print("Hi, my name is $name");
}
}
void main() {
var player = Player("PL", 500);
player.sayHello();
var player2 = Player("YJ", 100);
player2.sayHello();
}
한 번 String name에다가 선언하면 final 이 있기 때문에 player2에 넣는 것이 불가능하지 않남....
궁금.............
>> 왜냐하면 새로운 객체이기 때문에!
마치 player1은 새로운 객체/ 새로운 존재
마치 다른 세계의 player객체 하나여서 다른 세계의 Player는 영향을 주지 않는다고 생각하면 될 것 가타.
복습
class Player {
late final String name;
late int xp;
// late, this value will be defined "late"
Player(String name, int xp) {
this.name = name;
this.xp = xp;
}
void sayHello() {
print("Hi, my name is $name");
// unless you made a variable named with 'name'
// we don't use like $this.name
}
}
void main() {
var player = Player("nico", 1500);
// we don't have to write like new Player();
player.sayHello();
var player2 = Player("Ronaldo", 3000);
player2.sayHello();
}
// if I don't want this to be modified
Player 생성자 부분에 집중해보자
Player(String name, int xp) {
this.name = name;
this.xp = xp;
}
이 부분이 Dart 에서는 아래와 같이 한 줄로 정리될 수 있다. (어메이징,,,!)
Player(this.name, this.xp);
반응형