class, mixin 알아보기

Gmini.Y·2023년 11월 29일

Dart 기본

목록 보기
2/4

오름캠프 flutter 과정에서 학습한 내용을 정리하는 시리즈 입니다.

Dart 는 객체지향 언어로 class 를 지원한다. 문법은 아래와 같다.

class IronMan {
  String name;
  int powerLevel;

  IronMan(this.name, this.powerLevel);

  void shoot() {
    print('$name is shooting guns!');
  }
}

IronMan(this.name, this.powerLevel) 는 constructor 함수로 클래스 생성시 초기화한다.

extends

추상화를 통한 상속이 가능하다. 이때는 extends 키워드를 사용한다. 문법은 아래와 같다.

abstract class IronMan {
  String name;
  String suitColor;

  IronMan(this.name, this.suitColor);

  // This is an abstract method. It must be implemented by subclasses.
  void fly();

  // This is an abstract method. It must be implemented by subclasses.
  void shootLasers();

  // This is an abstract method. It must be implemented by subclasses.
  void withStandDamage();
}

//@override 구문을 사용하여 abstract method 구현
class Mark50 extends IronMan {
  var flyHeight;

  Mark50(String name, String suitColor, this.flyHeight)
      : super(name, suitColor);
  
  void shootLasers() {
    print('$name is shooting laser!');
  }

  
  void fly() {
    print('$name is flying in $flyHeight');
  }

  
  void withStandDamage() {
    print('$name is getting damaged');
  }
}

void main() {
  Mark50 mark50 = Mark50("mark50", "red", 100);

  mark50.fly();
  mark50.shootLasers();
  mark50.withStandDamage();
}

mixin

여러 클래스의 계층에서 클래스 코드를 재사용한다. with 키워드와 함께 사용하며 mixin에는 생성자를 넣을 수 없다.
아래와 같이 사용하여 mixin만 넣어서 코드의 재사용성을 좋게 만들수 있다.

mixin Flyable on Animal {
  void fly() {
    print('I am flying');
  }
}

class Animal {
  String name;

  Animal(this.name);
}

class Bird extends Animal with Flyable {
  Bird(String name) : super(name);
}

void main() {
  var bird = Bird('Bird');
  bird.fly();
}

0개의 댓글