IT News/Flutter & Dart

Dart 상속(Inheritance)과 믹스인(Mixins) : extends, with

skyLove1982 2022. 3. 8. 22:44
반응형

Dart 에서는 클래스 상속을 할때에는 extends 키워드를 사용합니다.

Spacecraft 라는 클래스가 있고 이 클래스를 상속받는 Orbiter 클래스가 있습니다.

class Spacecraft {
  String name;
  DateTime? launchDate;

  // Read-only non-final property
  int? get launchYear => launchDate?.year;

  // Constructor, with syntactic sugar for assignment to members.
  Spacecraft(this.name, this.launchDate) {
    // Initialization code goes here.
  }

  // Named constructor that forwards to the default one.
  Spacecraft.unlaunched(String name) : this(name, null);

  // Method.
  void describe() {
    print('Spacecraft: $name');
    // Type promotion doesn't work on getters.
    var launchDate = this.launchDate;
    if (launchDate != null) {
      int years = DateTime.now().difference(launchDate).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

아래의 Orbiter 클래스는 Spacecraft 클래스를 상속 받습니다.

상속 받기 때문의 부모 클래스의 모든 변수와 함수를 사용할 수 있습니다.

 

상속(Inheritance) in Class : extends

class Orbiter extends Spacecraft {
  double altitude;

  Orbiter(String name, DateTime launchDate, this.altitude)
      : super(name, launchDate);
}

https://dart.dev/guides/language/language-tour#extending-a-class

 

믹스인(Mixins) in Mixin : with

mixin Piloted {
  int astronauts = 1;

  void describeCrew() {
    print('Number of astronauts: $astronauts');
  }
}

mixin (믹스인)은 여러 클래스 계층에서 코드를 재사용하기 위한 방법 이라고 합니다.

참고로 사용할 때에는 with 키워드를 사용합니다.

class PilotedCraft extends Spacecraft with Piloted {
  // ···
}

PilotedCraft 클래스는 이제 astronauts 변수와 describeCrew() 메쏘드를 가지게 됩니다.

https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins

 

ref : https://dart.dev/samples

 

반응형

'IT News > Flutter & Dart' 카테고리의 다른 글

Dart 언어에서 implements 예제  (2) 2022.03.10
Dart 에서 Sound null safety 예제(example)  (1) 2022.03.03
Dart : DateTime 날짜 시간  (0) 2022.03.03