Menu
Coddy logo textTech

다형성이란 무엇인가요?

Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 35번째.

다형성은 서로 다른 클래스의 객체들이 동일한 메서드에 대해 서로 다른 방식으로 응답할 수 있도록 하는 객체 지향 프로그래밍의 핵심 원칙입니다.

JavaScript에서 다형성은 자식 클래스가 부모 클래스의 메서드를 오버라이드(override)할 때 가장 흔하게 볼 수 있습니다.

speak() 메서드를 가진 간단한 부모 클래스를 만들어 보겠습니다:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
}

이제 Animal을 상속받는 자식 클래스를 만들어 보겠습니다:

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

또 다른 자식 클래스는 다음과 같습니다:

class Cat extends Animal {
  speak() {
    return `${this.name} meows`;
  }
}

각 자식 클래스는 speak() 메서드를 다르게 구현합니다. 이것이 바로 다형성의 실제 사례입니다!

이제 서로 다른 객체를 생성하고 각각에 대해 동일한 메서드를 호출할 수 있습니다:

const animal = new Animal("Some animal");
const dog = new Dog("Rex");
const cat = new Cat("Whiskers");

console.log(animal.speak()); // Some animal이 소리를 냅니다
console.log(dog.speak());    // Rex가 짖습니다
console.log(cat.speak());    // Whiskers가 야옹하고 웁니다

세 객체 모두 speak() 메서드에 응답하지만, 각각 고유한 방식으로 동작합니다.

challenge icon

챌린지

부모 클래스 Notification과 두 개의 자식 클래스가 있는 알림 시스템이 있습니다. 여러분의 과제는 각 자식 클래스에 서로 다른 구현을 가진 send(message) 메서드를 추가하는 것입니다.

  1. EmailNotification 클래스에서, 메서드는 "Sending '(message)' via Email" 문자열을 반환해야 합니다.
  2. SMSNotification 클래스에서, 메서드는 "Sending '(message)' via SMS" 문자열을 반환해야 합니다.

치트 시트

다형성(Polymorphism)을 사용하면 서로 다른 클래스의 객체가 동일한 메서드에 대해 서로 다른 방식으로 응답할 수 있습니다. JavaScript에서 이는 일반적으로 자식 클래스가 부모 클래스의 메서드를 오버라이드(override)할 때 구현됩니다.

메서드를 가진 부모 클래스를 생성합니다:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
}

자식 클래스는 부모 메서드를 자신만의 구현으로 오버라이드할 수 있습니다:

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

class Cat extends Animal {
  speak() {
    return `${this.name} meows`;
  }
}

각 객체는 동일한 메서드에 대해 서로 다르게 응답합니다:

const animal = new Animal("Some animal");
const dog = new Dog("Rex");
const cat = new Cat("Whiskers");

console.log(animal.speak()); // Some animal makes a sound
console.log(dog.speak());    // Rex barks
console.log(cat.speak());    // Whiskers meows

직접 해보기

import { EmailNotification } from './email-notification.js';
import { SMSNotification } from './sms-notification.js';

// 테스트 코드 - 수정하지 마세요
const email = new EmailNotification();
const sms = new SMSNotification();

console.log(email.send("Hello!"));  // EmailNotification의 send()를 사용해야 함
console.log(sms.send("Hello!"));    // SMSNotification의 send()를 사용해야 함
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨