Dart #18 | Class(4) - Named Constructor

HyeonWooGa·2023년 10월 8일
0

Dart

목록 보기
19/25
post-thumbnail

Class Named Constructor


  • Named Constructor 개요
  • Named Constructor 사용

개요

  • Class 의 생성자를 Named 해주어서 다양한 목적/형태의 생성자를 명시적으로 추가할 수 있다.

사용

  • 기본 생성자인 클래스명 그 자체로 만든 생성자 이외의 클래스명.메소드이름() 형태로 만들 수 있습니다.
    • Named Constructor Parmaeters, Positional Constructor Parameters, 콜론을 활용할 수 있습니다.
  • 예시는 아래와 같습니다.
// Named Constructor Parameters

//// Class 정의
class Player {
  String name;
  final String id;
  int xp;
  String team;

  Player({
    required this.name,
    required this.id,
    required this.xp,
    required this.team,
  });

  // Named Constructor; Named Constructor Parameters 사용
  Player.createChristiansPlayer({
    required this.name,
    required this.id,
    this.xp = 0,
    this.team = 'Christians',
  });

  // Named Constructor; Named Constructor Parameters & 콜론 사용
  Player.createNonChristianPlayer({
    required String name,
    required String id,
  })  : this.name = name,
        this.id = id,
        this.team = 'Non Christians',
        this.xp = 0;
  
  // Named Constructor; Positional Constructor Parameters 사용
  Player.createUnknownPlayer(this.name, this.id, [this.xp = 0, this.team = 'Unknown']);

  void sayHello() {
    print('Hello I\'m $name($id) from $team team');
  }
}

void main() {
  // 기본 Constructor
  var player1 = Player(
    name: 'Park',
    team: 'Christians',
    id: 'yeonwoopark22',
    xp: 1500,
  );

  // Named Constructor; Named Constructor Parameters 사용
  var player2 = Player.createChristiansPlayer(name: 'Lee', id: 'igh1482');

  // Named Constructor; Named Constructor Parameters & 콜론 사용
  var player3 = Player.createNonChristianPlayer(name: 'Choi', id: 'choi77');
  
  // Named Constructor; Positional Constructor Parameters 사용
  var player4 = Player.createUnknownPlayer('Ryu', 'rjy90');
  
  // 각각의 생성자로 생성된 인스턴스 메소드 사용하여 Print; 모두 정상 동작
  player1.sayHello();
  player2.sayHello();
  player3.sayHello();
  player4.sayHello();
}

학습 중에 작성된 내용이므로 잘못되거나 부족한 내용이 있을 수 있습니다.

profile
Aim for the TOP, Developer

0개의 댓글