[TypeScript]_Class

hanseungjune·2023년 3월 4일
0

비전공자의 IT준비

목록 보기
52/68
post-thumbnail

📌 코드 해석

// 접근 제한자(Access modifier) - public, protected, private
/*
public - 자식 클래스, 클래스 인스턴스 모두 접근 가능(작성하지 않아도 자동으로 적용)
protected - 자식 클래스에서 접근 가능
private - 해당 클래스 내부에서만 접근 가능
*/

// Car 클래스 정의
class Car {
  // readonly 키워드를 사용하여 변수를 상수화
  readonly name: string = "car";
  // 일반 변수 선언
  color: string;
  // static 키워드를 사용하여 클래스 레벨에서 변수 선언
  static wheels = 4;
  // 생성자 함수
  constructor(color:string, name) {
    this.color = color;
    this.name = name // readonly 변수에 값을 할당
  }
  // 메소드 함수
  start() {
    console.log("start");
    console.log(this.name);
    console.log(Car.wheels);
  }
}

// Car 클래스를 상속한 Bmw 클래스 정의
class Bmw extends Car {
  // 생성자 함수
  constructor(color: string) {
    super(color, name); // 부모 클래스의 생성자 함수 호출
  }
  // 메소드 함수
  showName() {
    console.log(super.name);
  }
}

// Bmw 클래스를 사용하여 z4 객체 생성
const z4 = new Bmw("black", "zzzz4");
console.log(z4.name); // "zzzz4"
console.log(Car.wheels); // 4

먼저 주석에서 설명한 것과 같이 접근 제한자에는 public, protected, private가 있습니다. 이 코드에서는 readonly, static도 사용되었습니다.

  • readonly: 해당 속성은 값을 읽을 수만 있고, 변경할 수 없습니다. 이 코드에서 name 속성은 생성자에서 값이 할당되면 변경할 수 없습니다.
  • static: 해당 속성은 클래스 자체에 속하며, 인스턴스를 생성하지 않고도 클래스명으로 직접 접근 가능합니다. 이 코드에서 wheels 속성은 클래스 자체에 속하며, Car.wheels와 같이 접근할 수 있습니다.

또한 이 코드에서는 상속(inheritance)도 사용되었습니다. Bmw 클래스는 Car 클래스를 상속받고 있습니다. super() 키워드를 이용하여 부모 클래스의 생성자를 호출할 수 있으며, super 키워드를 이용하여 부모 클래스의 속성과 메서드에 접근할 수 있습니다.

이 코드는 Car 클래스를 상속받은 Bmw 클래스를 생성하고, Bmw 클래스의 인스턴스인 z4를 생성하여 출력하는 코드입니다. 하지만 Bmw 클래스의 생성자에서 name을 인자로 전달받지 않고 있기 때문에, 실행시 오류가 발생할 것입니다. 이 오류를 수정하려면 Bmw 클래스의 생성자에서 name 인자를 전달받도록 수정하면 됩니다.

, 이전 질문에서 작성해 주신 내용을 참고하여, 다시 주석을 달아 코드를 작성해보겠습니다.

typescript
Copy code
// 추상 class
abstract class Car {
  color: string;
  
  // 추상 클래스는 추상 메서드를 가질 수 있습니다.
  // 추상 메서드는 구현하지 않고 선언만 할 수 있습니다.
  // 추상 메서드는 하위 클래스에서 반드시 구현되어야 합니다.
  abstract doSomething(): void;
  
  constructor(color: string) {
    this.color = color;
  }

  start() {
    console.log("start");
  }
}

// 추상 클래스를 상속받은 하위 클래스는 추상 클래스의 추상 메서드를 반드시 구현해야 합니다.
class Bmw extends Car {
  constructor(color: string) {
    super(color);
  }

  // 추상 메서드를 구현합니다.
  doSomething() {
    alert(3);
  }
}

// 추상 클래스는 직접 인스턴스화 할 수 없습니다.
// const car = new Car("red");

// 추상 클래스를 상속받은 하위 클래스의 인스턴스를 생성합니다.
const z4 = new Bmw("black");
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글