Skip to content

Instantly share code, notes, and snippets.

@dicenull
Created March 14, 2024 08:14
Show Gist options
  • Save dicenull/6961d131caf62466e0649250f2a9ef5c to your computer and use it in GitHub Desktop.
Save dicenull/6961d131caf62466e0649250f2a9ef5c to your computer and use it in GitHub Desktop.
class Spacecraft {
// プロパティ
String name;
DateTime? launchDate;
// 読み込み専用プロパティのgetter
int? get launchYear => launchDate?.year;
// コンストラクタ。`this.`の糖衣構文によって引数をメンバに代入しています
Spacecraft(this.name, this.launchDate) {
// コンストラクタで初期するコードを記述します
}
// 名前付きコンストラクタ。`this(name, null)`はデフォルトコンストラクタを呼び出します。
Spacecraft.unlaunched(String name) : this(name, null);
// メソッド
void describe() {
// '$name'は文字列補完によって変数の内容を文字列に変換しています。
print('Spacecraft: $name');
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
void main() {
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();
var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment