docs

TOP(About this memo)) > 一覧(Dart) > クラス(メンバー)

クラス・オブジェクト

Dart is an object-oriented language with classes and mixin-based inheritance. Every object is an instance of a class, and all classes except Null descend from Object. Mixin-based inheritance means that although every class (except for the top class, Object?) has exactly one superclass, a class body can be reused in multiple class hierarchies. Extension methods are a way to add functionality to a class without changing the class or creating a subclass. Class modifiers allow you to control how libraries can subtype a class.

(参考)(IMO)プロパティとインスタンス変数の違いは?

インスタンス変数(instance variables)

class A {
  A(this._test, this._test2, this._test3);
  int _test;
  //int get _test => _test + 1; //_testという名前は既に存在するためerror(変数と衝突している?それともデフォルトで作成されるsetterと衝突?)
  int get test => _test + 10;// 自分で定義したgetter
  int get test2 => _test + 11;// 自分で定義したgetter
  set test(int test){_test += 5;}// 自分で定義したsetter
  set test2(int test){_test += 6;}// 自分で定義したsetter
  
  final int _test2; // finalは初期化が必要
  final int? _test3; // finalはnullableでも初期化が必要
  //set test3(int test){_test2 = 5;}// finalなプロパティを変えることはできない。

  int? x;// nullとして初期化される。
  late int z;// lateはコンストラクタによる初期化は不要。
  late final int l;// finalをつけた場合も同様。

  int m = 0;// 0として初期化される。
}
void main() {
  var a = A(5,4,3);
  // var a = A(5,4); // エラー
  a._test = 1;// すべてのインスタンスは暗黙的にsetterが作成される。
  print(a._test);// すべてのインスタンスは暗黙的にgetterが作成される。
  print(a.test);
  print(a.test2);
  a.test = 100000;
  print(a._test);
  a.test = 1000000;
  print(a._test);
  print(a.z); // 初期化未済のため実行時エラー
}

instance method

static variable

Static variables aren’t initialized until they’re used.

static method

classのスコープ

(IME) プライベートクラスの中のメンバーはプライベートとした方が良いか?

(参考)Dartでのprivateフィールドの実現

void main() {
  var b2 = B2(4);
  print(b2._test);// 
}
class B2 {
  const B2(this._test);
  final int _test;
}

(参考) Dartのsetter