42일차[상속 / super / 오버라이드 / 다형성]

진하의 메모장·2025년 3월 7일
2

공부일기

목록 보기
48/66
post-thumbnail

2025 / 03 / 07

오늘 수업 시간에는 클래스의 상속과 super 클래스의 개념과 사용 방법을 배웠습니다.
super 클래스는 학교에서 수업 했을 때 듣기만 하고 넘어간 부분이라 이번에 배우면서 생소한 부분도 많았습니다. 오버라이드와 다형성은 자주 접하고 배우기도 했는데 헷갈릴 가능성이 있어서 오버라이드에 대해 정리하고 넘어가도록 하겠습니다.



💌 클래스의 상속

Inheritance

  • 부모 클래스의 속성(프로퍼티)와 행위(메서드)를 자식 클래스로 전달하는 기능입니다.
  • 자식 클래스는 부모 클래스의 기능을 그대로 사용할 수 있습니다.
  • 필요에 따라 자식 클래스에서 추가적인 기능을 덧붙일 수 있습니다.

1. extends 키워드

  • 자식 클래스가 부모 클래스를 상속받기 위해서는 extends 키워드를 사용합니다.
  • 자식 클래스는 부모 클래스에서 정의한 프로퍼티와 메서드를 그대로 사용할 수 있습니다.
// 부모 클래스 Car 정의
class Car {
   name: string;
   year: number;

   // 생성자
   constructor(name: string, year: number) {
      this.name = name;
      this.year = year;
   }
}

// 자식 클래스 ElectricCar - Car 클래스를 상속받음
class ElectricCar extends Car {
   charge(): string {
      return `${this.name}이 충전되었습니다.`;
   }
}

// 자식 클래스 GasCar - Car 클래스를 상속받음
class GasCar extends Car {
   refuel(): string {
      return `${this.name}이 주유되었습니다.`;
   }
}

// 인스턴스 생성
const tesla = new ElectricCar("Tesla", 2010);
const bmw = new GasCar("BMW", 2013);

// 메서드 호출
console.log(tesla.charge());  // Tesla이 충전되었습니다.
console.log(bmw.refuel());   // BMW이 주유되었습니다.
  • Car 클래스는 기본적인 차의 이름(name)과 생산년도(year)를 프로퍼티로 가지고 있습니다.
  • ElectricCar와 GasCar는 각각 Car 클래스를 상속받습니다.
  • 각자 charge( )와 refuel( )이라는 메서드를 추가로 정의하고 있습니다.
  • tesla는 ElectricCar의 인스턴스로 charge( ) 메서드를 사용할 수 있습니다.
  • bmw는 GasCar의 인스턴스로 refuel( ) 메서드를 사용할 수 있습니다.


2. instanceof 연산자

  • 특정 객체가 특정 클래스의 인스턴스인지 확인하는 데 사용됩니다.
  • 객체가 특정 클래스 또는 클래스의 상속 계층에 속하는지 확인하는 데 유용합니다.
// instanceof를 사용하여 객체가 특정 클래스의 인스턴스인지 확인

// true, tesla는 Car 클래스의 인스턴스
console.log(tesla instanceof Car);        

// true, tesla는 ElectricCar 클래스의 인스턴스
console.log(tesla instanceof ElectricCar); 

// true, bmw는 Car 클래스의 인스턴스
console.log(bmw instanceof Car);    

// false, bmw는 ElectricCar의 인스턴스가 아님
console.log(bmw instanceof ElectricCar); 
  • tesla instanceof Car는 true입니다.
  • tesla는 ElectricCar 클래스의 인스턴스이고, ElectricCar는 Car 클래스를 상속받았기 때문입니다.

  • bmw instanceof ElectricCar는 false입니다.
  • bmw는 GasCar 클래스의 인스턴스이고, ElectricCar의 인스턴스가 아니기 때문입니다.


3. 장점

1. 코드 재사용성

  • 부모 클래스에서 공통된 속성과 메서드를 정의하고, 자식 클래스는 이를 그대로 사용할 수 있기 때문에 코드가 간결하고 재사용성이 높습니다.

2. 확장성

  • 부모 클래스의 기능을 확장하거나 오버라이딩하여 새로운 기능을 추가할 수 있습니다.

3. 유지보수 용이성

  • 부모 클래스에서 수정하면 자식 클래스에서 자동으로 반영되어 유지보수가 용이합니다.


💌 super

  • 자식 클래스에서 부모 클래스의 생성자나 메서드를 호출할 때 사용합니다.
  • 자식 클래스가 부모 클래스의 속성이나 메서드를 사용할 수 있게 해줍니다.
  • 자식 클래스에서 부모 클래스의 생성자를 호출할 때 super( )를 사용합니다.
  • 부모 클래스의 메서드를 호출할 때도 super.메서드명( )을 사용합니다.
class Car {
   name: string;

   constructor(name: string) {
      this.name = name;
   }

   start() {
      console.log(`${this.name}가 출발합니다.`);
   }
}

class ElectricCar extends Car {
   battery: number;

   constructor(name: string, battery: number) {
      super(name);  // 부모 클래스의 생성자를 호출
      this.battery = battery;
   }

   start() {
      super.start();  // 부모 클래스의 start() 메서드 호출
      console.log(`배터리 용량은 ${this.battery}입니다.`);
   }
}

const tesla = new ElectricCar("테슬라", 100);
tesla.start();  // 테슬라가 출발합니다. 배터리 용량은 100입니다.
  • ElectricCar에서 super(name)을 통해 부모 클래스인 Car의 생성자를 호출하고, super.start( )로 부모 클래스의 start 메서드를 호출합니다.


💌 오버라이드

Override - 부모 클래스 메서드 수정

  • 부모 클래스에서 정의한 메서드를 자식 클래스에서 새롭게 정의하는 것입니다.
  • 부모의 메서드를 수정하거나 추가적인 기능을 덧붙일 수 있습니다.
class Car {
   name: string;

   constructor(name: string) {
      this.name = name;
   }

   start() {
      console.log(`${this.name}가 출발합니다.`);
   }
}

class ElectricCar extends Car {
   battery: number;

   constructor(name: string, battery: number) {
      super(name);
      this.battery = battery;
   }

   // 부모 클래스의 start() 메서드를 오버라이드
   start() {
      super.start();  // 부모 클래스의 start() 호출
      console.log(`배터리 용량은 ${this.battery}입니다.`);
   }
}

const tesla = new ElectricCar("테슬라", 100);
tesla.start();  // 테슬라가 출발합니다. 배터리 용량은 100입니다.
  • ElectricCar 클래스에서 부모 클래스인 Car의 start( ) 메서드를 오버라이드해서 배터리 용량을 추가로 출력하는 기능을 넣었습니다.


💌 다형성

부모 타입으로 자식 객체 다루기

  • 부모 클래스의 타입으로 자식 클래스의 객체를 다룰 수 있게 해주는 개념입니다.
  • 부모 클래스의 메서드는 자식 클래스에서 다르게 동작할 수 있습니다.(유연성 증가)
class Parent {
   name: string;

   constructor(name: string) {
      this.name = name;
   }

   dance() {
      console.log(`${this.name}님이 춤을 춥니다.`);
   }
}

class Child extends Parent {
   age: number;

   constructor(name: string, age: number) {
      super(name);
      this.age = age;
   }

   sing() {
      console.log(`${this.name}${this.age}세, 노래를 부르고 있습니다.`);
   }
}

const father = new Parent("아빠");
const son = new Child("아들", 22);

// 다형성: 부모 타입으로 자식 객체를 다룰 수 있다.
let person: Parent;
person = father;  // person은 Parent 타입, father는 Parent 객체
person.dance();    // 아빠님이 춤을 춥니다.

person = son;  // person은 여전히 Parent 타입, son은 Child 객체
person.dance();    // 아들님이 춤을 춥니다. (다형성 적용)
  • person은 Parent 클래스 타입인데, son(자식 클래스의 인스턴스)을 할당할 수 있습니다.
  • 부모 클래스의 메서드를 자식 클래스의 객체에서 호출할 수 있게 됩니다.


💌 실습 예제

Car 클래스를 상속받는 ElectricCar 클래스를 만들고, 다음 속성을 추가하시오.

  • batteryCapacity (숫자): 배터리 용량
  • 생성자에서 brand, batteryCapacity(기본값 100)을 받아서 초기화
  • 배터리의 남은 용량을 확인하는 getter 추가
  • charge( ) 메서드 추가: 배터리 용량을 100으로 설정
class Car {
   brand: string;
   speed: number = 0;

   constructor(brand: string) {
      this.brand = brand;
   }

   accelerate(amount: number): void {
      this.speed += amount;
   }

   brake(amount: number): void {
      this.speed -= amount;
   }
}

// ElectricCar 클래스는 Car 클래스를 상속받음
class ElectricCar extends Car {
   batteryCapacity: number = 50; // 배터리 용량 초기값

   constructor(brand: string) {
      super(brand);  // 부모 클래스(Car)의 생성자 호출
   }

   // 배터리 용량을 반환하는 getter
   get batteryStatus(): number {
      return this.batteryCapacity;
   }

   // 배터리 충전 메서드
   charge(): void {
      this.batteryCapacity = 100; // 배터리 용량을 100으로 설정
      console.log(`현재 배터리 : ${this.batteryCapacity}`);
   }
}

const tesla = new ElectricCar("Tesla");

// 부모 클래스에서 상속받은 속성 사용
console.log(tesla.brand); // "Tesla"

// 배터리 상태를 반환하는 getter 사용
console.log(tesla.batteryStatus); // 50

tesla.charge(); // 배터리 충전 후 상태 출력
console.log(tesla.batteryCapacity); // 100



42일차 후기

  • 학교 다닐 때 배웠었는데 다 까먹은 건 아닌지 어렵지는 않았습니다.
  • 오버로딩과 오버라이딩을 헷갈리지 않게 조심해야겠습니다.
  • 자식 클래스에서 부모 클래스의 메서드를 재정의하는 것 : 오버 라이드
  • 같은 이름의 함수가 매개변수의 개수나 타입에 따라 다르게 동작하는 것 : 오버 로딩
  • 다형성을 이해하는 과정에서 조금 어려움이 있었는데.. 다행히 해결했습니다!
  • 다형성에서 부모 클래스에서 정의된 속성이나 메서드를 제외한 자식 클래스에서 새로 추가된 부분은 부모 클래스 타입에서는 접근할 수 없다고 합니다.
  • 오늘도 여러가지 의문점을 해결할 수 있어서 다행이라고 생각합니다. 화이팅!! (´∀`*)☆
profile
૮꒰ ྀི〃´꒳`〃꒱ა

0개의 댓글