LoginSignup
0
2

More than 3 years have passed since last update.

Dartのクラス

Posted at

Dartのクラス

DartのクラスはC#なんかとはいろいろと違うみたい。わからない事だらけ。

新しいことが理解できたら追記していくことにする。

class Person
{
    //-------------------------------------------------------------
    // Publicメンバ
    //-------------------------------------------------------------
    String firstName;
    String lastName;

    //-------------------------------------------------------------
    // Privateメンバ
    //-------------------------------------------------------------
    int    _age;

    //-------------------------------------------------------------
    // コンストラクタ
    //-------------------------------------------------------------
    // this + メンバ変数名の引数で、各メンバ変数に値を代入可能。
    Person(this.firstName, this.lastName)
    {
        _age = 0;
    }

    //-------------------------------------------------------------
    // 名前付きコンストラクタ
    //-------------------------------------------------------------
    Person.newBorn()
    {
        this.firstName = "名前はまだない";
        this.lastName  = "吾輩は人である";
        this._age      = 0;
    }

    //-------------------------------------------------------------
    // Call関数
    //-------------------------------------------------------------
    // インスタンス名で呼び出せる特殊な関数
    call()
    {
        return "$lastName $firstName, age $_age.";
    }

    // セッター
    void set age(int value) => _age = value;

    // ゲッター
    int get age => _age;

}

class Boxer extends Person
{
    double _weight;

    Boxer(String first, String last, double weight):
        _weight = weight,
        super(first, last);

    Boxer.newBorn():
        this._weight   = 48.0,
        super("I have no ring name yet", " I'm Boxer");

    // factoryを付けるとfactoryメソッドとしてインスタンスを返せる。
    factory Boxer.instance()
    {
        Boxer instance = new Boxer.newBorn();
        return instance;
    }

    Introduce() => "$lastName $firstName, age  $_age. I'm Boxer";

    void setAge(int value) => _age = value;
    void getAge() => _age;

    @override
    Call() {
        return Introduce();
    }
}

main()
{
    Person man = Person("Take", "");
    man.age = 30;

    Boxer red_boxer = Boxer("Yuto", "", 15);
    //red_boxer.age = 7;                            // 親クラスのセッターは呼べない?
    red_boxer.setAge(7);

    Boxer blue_boxer = Boxer.instance();
    blue_boxer.setAge(18);

    print(man());
    print(red_boxer.Introduce() );
    print(blue_boxer());                            // 子クラスのCall関数を呼べない?

}

// 実行結果
 Take, age 30.
 Yuto, age  7. I'm Boxer
 I'm Boxer I have no ring name yet, age 18.

[参考サイト]

Flutter入門のためのDart入門

0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2