메서드 오버라이딩
Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 110개 중 38번째.
method 오버라이딩은 자식 class가 parent class에 이미 존재하는 method에 대한 자체 구현을 제공할 때 발생합니다. 이를 통해 서브클래스는 동일한 method 시그니처를 유지하면서 상속된 동작을 사용자 지정할 수 있습니다.
자식 클래스에서 부모 클래스의 메서드와 같은 이름과 매개변수로 메서드를 정의하면 자식 클래스의 버전이 대신 사용됩니다:
class Animal {
String name;
Animal(this.name);
void speak() {
print('$name makes a sound');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
void speak() {
print('$name barks: Woof!');
}
}
void main() {
var animal = Animal('Generic');
var dog = Dog('Buddy');
animal.speak(); // Generic이 소리를 낸다
dog.speak(); // Buddy가 짖는다: Woof!
}speak()을 Dog 인스턴스에서 호출하면 Dart는 Animal의 버전이 아니라 Dog의 버전을 실행합니다. 자식 클래스가 parent의 method를 재정의했습니다.
super를 오버라이딩과 함께 사용하여 부모의 동작을 대체하는 대신 확장할 수도 있습니다:
class Cat extends Animal {
Cat(String name) : super(name);
void speak() {
super.speak(); // 부모의 버전을 먼저 호출
print('$name also purrs');
}
}이 패턴을 사용하면 기존 기능을 기반으로 확장할 수 있습니다. 핵심 규칙은 간단합니다. 자식 클래스에서 동일한 메서드 이름과 매개변수를 사용하면 자식 인스턴스에서 호출될 때 부모의 구현을 대체합니다.
챌린지
쉬움parent method를 재정의하여 동작을 사용자 지정하는 child class를 보여 주는 notification system을 만들어 보겠습니다. 각기 고유한 방식으로 message를 전달하는 다양한 notification type을 만들게 됩니다.
code를 두 개의 file로 구성합니다:
notification.dart: 여기에서 notification hierarchy를 Define합니다:Notificationclass(parent)에String title과String message를 포함합니다. 두 값을 받는 constructor와Notification: [title] - [message]를 Print하는send()method를 포함하세요.EmailNotificationclass는Notification을 extends하고String recipientproperty를 추가합니다.send()method를 Override하여Sending email to [recipient]: [title] - [message]를 Print하세요.PushNotificationclass는Notification을 extends하고String deviceIdproperty를 추가합니다.send()method를 Override하여 먼저super를 사용해 parent의send()를 Call한 다음, 다음 line에Pushed to device: [deviceId]를 Print하세요.
main.dart: notification file을 import하고 method overriding이 실제로 동작하는 모습을 보여 줍니다:- title이
'Alert'이고 message가'System update available'인 baseNotification을 Create합니다. - 그
send()method를 Call합니다. - empty line을 Print합니다.
- title이
'Welcome', message가'Thanks for signing up!', recipient가'user@example.com'인EmailNotification을 Create합니다. - 그
send()method를 Call합니다. - empty line을 Print합니다.
- title이
'Reminder', message가'Meeting in 10 minutes', deviceId가'DEVICE-001'인PushNotification을 Create합니다. - 그
send()method를 Call합니다.
- title이
EmailNotification은 parent의 동작을 완전히 대체하는 반면, PushNotification은 먼저 super.send()를 Call하여 동작을 확장한다는 점에 주목하세요. 필요에 따라 두 접근 방식 모두 method를 Override하는 유효한 방법입니다.
예상 output:
Notification: Alert - System update available
Sending email to user@example.com: Welcome - Thanks for signing up!
Notification: Reminder - Meeting in 10 minutes
Pushed to device: DEVICE-001직접 해보기
import 'notification.dart';
void main() {
// TODO: Create a base Notification with title 'Alert' and message 'System update available'
// send() 메서드를 호출하세요
// TODO: 빈 줄을 출력하세요
// TODO: EmailNotification을 다음 내용으로 생성하세요:
// - title: 'Welcome'
// - message: 'Thanks for signing up!'
// - recipient: 'user@example.com'
// send() 메서드를 호출하세요
// TODO: 빈 줄을 출력하세요
// TODO: PushNotification을 다음 내용으로 생성하세요:
// - title: 'Reminder'
// - message: 'Meeting in 10 minutes'
// - deviceId: 'DEVICE-001'
// send() 메서드를 호출하세요
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러