본문 바로가기
개발해보겡/Flutter

Dart with (Mixin) 이해하기

by 취미야취미 2023. 1. 7.
728x90
반응형

클래스를 상속받는 것 외에 

with를 통해 다른 클래스의 멤버 변수와 멤버 함수를 사용할 수 있습니다.

with (Mixin)을 사용해 다른 클래스의 멤버 함수를 사용해보겠습니다.

class Human {
  String name;
  int age;

  Human({
    required this.name,
    required this.age,
  });

  void intro() {
    print("My name is $name and I'm $age years old.");
  }
}

class Student extends Human with highScore{
  final int number;

  Student({
    required String name,
    required int age,
    required this.number,
  }) : super(name: name, age: age);

  @override
  void intro() {
    super.intro();
    print("My Student-ID is $number");
  }
}

class highScore {
  int score = 100;

  void exam() {
    print("My score is $score");
  }
}

void main() {
  var student = Student(
    name: 'name',
    age: 19,
    number: 2020031432,
  );
  student.intro();
  // Mixin
  student.exam();
}

Human 클래스를 상속받은 Student 클래스 객체인 student가

highScore 클래스의 exam() 멤버 함수를 메서드로 호출하여 

잘 작동하는 것을 확인할 수 있습니다.

그렇다면 highScore 클래스의 경우에는 Student 클래스를 Mixin 으로 사용할 수 있을까요?

// The class 'Student' can't be used to as a mixin
// because it declares a constructor
class highScore with Student {
  int score = 100;

  void exam() {
    print("My score is $score");
  }
}

Student 클래스는 생성자를 사용하기 때문에 Mixin 으로 사용될 수 없습니다.

Mixin을 사용하는 경우 

하나의 클래스를 사용하기 보다는 여러 개의 클래스를 사용할 때

유용하다고 합니다.

감사합니다.

반응형