[Language/TypeScript] 좔상 클래슀

2023. 7. 27. 14:02γ†πŸ”€ Language/TypeScript

μ •μ˜: μΈμŠ€ν„΄μŠ€ν™” ν•  수 μ—†λŠ” 클래슀둜 μžμ‹ ν΄λž˜μŠ€μ—κ²Œ μΆ”μƒν•¨μˆ˜λ₯Ό λ°˜λ“œμ‹œ λ§Œλ“€λ„λ‘ κ°•μ œν•¨.

abstract class Shape {
  abstract getArea(): number; // 좔상 ν•¨μˆ˜ μ •μ˜!!!

  printArea() {
    console.log(`λ„ν˜• 넓이: ${this.getArea()}`);
  }
}

class Circle extends Shape {
  radius: number;

  constructor(radius: number) {
    super();
    this.radius = radius;
  }

  getArea(): number { // μ›μ˜ 넓이λ₯Ό κ΅¬ν•˜λŠ” 곡식은 파이 X λ°˜μ§€λ¦„ X λ°˜μ§€λ¦„
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    super();
    this.width = width;
    this.height = height;
  }

  getArea(): number { // μ‚¬κ°ν˜•μ˜ 넓이λ₯Ό κ΅¬ν•˜λŠ” 곡식은 κ°€λ‘œ X μ„Έλ‘œ
    return this.width * this.height;
  }
}

const circle = new Circle(5);
circle.printArea();

const rectangle = new Rectangle(4, 6);
rectangle.printArea();

μ‚¬μš©λͺ©μ 

  • μžμ‹ ν΄λž˜μŠ€μ— λ°˜λ“œμ‹œ ν¬ν•¨μ‹œκ³  싢은 λ‚΄μš©μ„ abstract func톡해 μ§€μ •
  • μžμ„Έν•œ λ‚΄μš©μ„ μžμ‹ ν΄λž˜μŠ€μ—μ„œ κ΅¬ν˜„ν•  λ•Œ μ‚¬μš©