Dart 언어 오답노트 : 21. required super

샤워실의 바보·2023년 10월 25일
0
post-thumbnail

Dart의 생성자 및 상속

Dart에서 클래스를 확장(상속)할 때, 자식 클래스는 부모 클래스의 생성자를 호출해야 합니다. Dart 2.17 버전 이후로는 super 키워드를 사용하여 부모 클래스의 생성자를 더 간결하게 호출할 수 있게 되었습니다. 이것이 바로 required super.name 구문의 역할입니다.

Player 클래스의 두 가지 생성자 비교

1. Dart 2.17 이전의 방식

Player({
  required this.team,
  required String name,
}) : super(name: name);
  • this.team: Player 클래스의 team 속성을 초기화합니다.
  • String name: 메서드 매개변수로 name을 받아들입니다.
  • super(name: name): 부모 클래스인 Human의 생성자를 호출하며, 받아온 name 값을 전달합니다.

2. Dart 2.17 이후의 방식

Player({
  required this.team,
  required super.name,
});
  • this.team: Player 클래스의 team 속성을 초기화합니다.
  • required super.name: 부모 클래스인 Humanname 속성을 초기화하며, 필수 매개변수로 설정합니다.
class Idol {
  final String name;
  final int membersCount;

  Idol({
    required this.name,
    required this.membersCount,
  });

  void sayName() {
    print('저희는 $name입니다.');
  }

  void sayMembersCount() {
    print('$name은/는 $membersCount명의 멤버가 있습니다.');
  }
}

class BoyGroup extends Idol {
  BoyGroup(String name, int membersCount)
      : super(name: name, membersCount: membersCount);
}

void main() {
  BoyGroup bts = BoyGroup('BTS', 7);
  bts.sayMembersCount(); // BTS은/는 7명의 멤버가 있습니다.
  bts.sayName(); // 저희는 BTS입니다.
}

두 방식의 유사점과 차이점

  • 유사점: 두 방식 모두 Player 클래스가 생성될 때 team 속성과 Human 클래스의 name 속성을 초기화합니다.
  • 차이점: Dart 2.17 이후의 방식은 보다 간결하며, 부모 클래스의 생성자 호출 구문을 생략할 수 있게 해줍니다.

positional parameter에서도 가능한가?

Dart 2.17 이후의 required super 구문은 named parameter에서 주로 사용됩니다. positional parameter에서는 이 구문을 사용할 수 없습니다.

position parameter를 사용할 때는 여전히 기존 방식으로 부모 클래스의 생성자를 호출해야 합니다. 예를 들어:

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

class Player extends Human {
  final int number;
  
  Player(this.number, String name) : super(name);
}

void main() {
  var player = Player(7, 'John');
  print(player.name);  // 출력: John
}

위의 예시에서 Player 클래스는 Human 클래스를 상속받고 있습니다. Player 클래스의 생성자는 numbername 두 개의 positional parameter를 받습니다. name은 부모 클래스인 Human의 생성자로 전달되어야 하므로 : super(name) 구문을 사용해 호출합니다.

required super 구문은 named parameter와 함께 사용되도록 설계되었기 때문에, positional parameter에서는 이를 사용할 수 없습니다. 따라서 positional parameter를 사용하는 상황에서는 여전히 기존 방식을 사용해야 합니다.

결론

required super.name 구문을 사용하면 코드가 더 간결해지고, 부모 클래스의 생성자를 명시적으로 호출할 필요가 없게 됩니다. 이는 코드의 가독성을 향상시키며, 특히 부모 클래스의 생성자에 많은 매개변수가 있을 때 유용합니다.

profile
공부하는 개발자

0개의 댓글