ex)
void main() {
int a = 5; // 스택에 정수 변수 a가 할당됨
// 힙에 객체를 할당
MyClass myObject = MyClass();
}
class MyClass {
// MyClass 객체의 속성들이 힙에 할당됨
}
class MyClass {
// 기본 생성자
MyClass() {
// 생성자의 내용
}
}
Cleric(this.name,this.hp,this.mp);
Cleric({
this.name,
required this.hp,
required this.mp,
});
}
(생성자에 {} 를 사용하면 Named Parameter, null을 허용하지 않으면 required를 붙여야함)
위와같은 Named Argument Constructor을 자동생성 해주는 안드로이드 스튜디오의 플러그인이 있다.

플러그인 설치 후 control(^) + enter => Named Argument Constructor 선택
class Hero {
String name;
int hp;
Sword? sword;
// 필수 파라미터와 옵셔널 파라미터를 동시에 사용할 수 있다
// 필수 parameter와 named(옵셔널) parameter를 동시에 사용할경우 필수 parameter가 앞에 와야됨
// 마지막 파라미터 뒤에 콤마를 찍을 수 없음
Hero(this.name, this.hp, {this.sword});
Cleric(
this.name, {
this.hp = 50,
this.mp = 10,
});
(기본값을 지정 할 때는 required를 제거해야함)
final cleric1 = Cleric("아서스", hp: 40, mp: 5);
생성자를 다음과 같이 생성 하였을때, 다음과 같은 인스턴스들을 생성 할 수 있다
Cleric(
this.name, {
this.hp = Cleric.maxHP,
this.mp = Cleric.maxMP,
});
final cleric1 = Cleric("아서스", hp: 40, mp: 5);
final cleric2 = Cleric("아서스", hp: 40);
final cleric3 = Cleric("아서스");
ex)
class Cleric {
static const int maxHP = 50;
}
위와같이 변수 maxHP가 Cleric 클래스 안에 선언되었지만
maxHP는 Cleric의 인스턴스가 아닌 모든 인스턴스가 공유하는 하나의 저장공간을 갖고 있다.
위 예제는 다음과 같이 Top level 변수와도 비슷하다.
const int maxHP = 50;
class Cleric {
}