1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

クラスのこと改めて勉強します

Last updated at Posted at 2023-07-14

MVVMの理解を深めていこうというところでabstractとかimplementsとか聞いたことない、もしくは見たことあるけど見て見ぬ振りしてたというようなものがいくつか見受けられたのでその辺りも含めて改めて学習していく。

extends (継承)

言わずと知れたextendsを使うことでクラスを継承できるというもの。
子クラスのコンストラクタのsuperで親クラスのコンストラクタも呼んでいる。
@overrideを使うことで親クラスのインスタンスやメソッドを上書きすることができる。

class Person {
  final String name;
  Person(this.name);
}

// Personクラスを継承
class Birthplace extends Person {
  String hometown;
  //superで親クラスのコンストラクタも呼んでいる
  Birthplace(String name, this.hometown) : super(name);

  @override
  void introduce() {
    print('私は$hometownに住んでいます。');
  }
}

void main() {
  final information = Birthplace('太郎', '札幌');
  information.introduce(); //私は札幌に住んでいます。
}

abstract (抽象)

abstract class クラス名 {
  String メソッド名();
}

上記のようにclassの前にabstractをつけて宣言されたクラスを抽象クラスと呼ぶ。
抽象クラスは継承されることを前提としたクラスでインスタンスかすることができない。
抽象メソッドという処理内容を記述できないメソッドを定義することができる。
「抽象的」と調べると出てきたかなり確信をついた一文↓
「共通した要素を抜き出して一般化していること、または具体性に欠けていて実態が明確ではないことである。」

implements

こちらのサイトがわかりやすかった↓

implementsをつけるとそのクラス(下記でいうPersonクラス)の変数やメソッドなどといった要素を必ず実装しなければならない。
変数やメソッドの実装を強制するという約束のようなもの。

class Person {
  final String name;
  Person(this.name);
  void introduce() {
    print('私の名前は$nameです。');
  }
}

class Birthplace implements Person {
  //強制実装!
  final String name;
  String hometown;
  Birthplace(this.name, this.hometown);
  //強制実装!
  void introduce() {
    print('私は$nameです。$hometownに住んでいます。');
  }
}

mixin, with

mixinを使うとクラスの拡張パックのようなもの(状態やメソッド)を定義できて、
withを使うことで拡張パックの内容をクラスに追加実装できるというイメージ。

mixin infomation{
  void askAge(){
    print('何歳ですか?');
  }

  void askHobby(){
    print('趣味は何ですか?');
  }
}

class Person with infomation {
  final String name; 
  Person(this.name);
}

↑これが
こうなるイメージ↓

class Person{
  final String name; 
  Person(this.name);

  void askAge(){
    print('何歳ですか?');
  }

  void askHobby(){
    print('趣味は何ですか?');
  }
}

これで忘れることはないだろう

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?