예시)
final hero1 = Hero(name: '홍길동', hp: 100)
final hero2 = hero1
hero2.hp = 200
print(hero1.hp) // 100(x) -> 200(o)
/*
- 인스턴스는 객체 생성 시 메모리에 저장된 값의 주소를 참조한다
- 따라서, hero1과 hero2는 같은 메모리의 주소를 참조하며
- hero2의 필드 값을 변경하면 hero1의 필드 값도 같이 변경된다
*/
: 클래스와 같은 이름을 가지는 함수로, 인스턴스 생성 시 사용된다
💡 타입 변수명 = 객체명(인수): 인스턴스 생성 시 매개변수에 값만 받아서 지정
💡 객체명(this.name, this.hp) → 객체명(‘홍길동’, 100): 인스턴스 생성 시 매개변수에 이름을 부여하는 것. {} 사용
💡객체명({this.name, this.hp}) → 객체명(name: ‘홍길동’, hp: 100): 인스턴스 생성 시 필수로 값을 지정해줘야하는 필드.
: static 키워드는 변수나 메소에 사용되며, 클래스가 메모리에 로딩될 때 자동으로 생성된다
class Hero {
static int money = 100; // static 키워드를 사용하여 필드 공유
String name;
int hp;
Hero({required this.name, required this.hp);
}
void main(){
print(Hero.money); // 100이 출력된다
}
class Hero {
static int money = 100; // static 키워드를 사용하여 필드 공유
String name;
int hp;
Hero({required this.name, required this.hp);
static void setRandomMoney(){
money = Random().nextInt(1000);
}
}
void main(){
Hero.setRandomMoney();
print(Hero.money); // 0 ~ 999 중에서 랜덤값으로 출력
}