Dziedziczenie i polimorfizm

Klasy i obiekty - JavaScript od podstaw: konsola (JavaScript)

`class Rectangle extends Shape` znaczy: prostokąt JEST figurą, dziedziczy jej pola i metody. Konstruktor klasy pochodnej najpierw woła `super(...)`, czyli konstruktor rodzica. Każda figura nadpisuje metodę `area` po swojemu, a `describe` z klasy bazowej korzysta z niej, nie wiedząc, jaka to figura. Pętla po tablicy różnych figur wywołuje tę samą metodę: to polimorfizm. `Square` dziedziczy po `Rectangle`, więc jest też prostokątem i figurą.

class Shape {
  constructor(name) {
    this.name = name;
  }

  area() {
    return 0;
  }

  describe() {
    return `${this.name}: pole ${this.area().toFixed(2)}`;
  }
}

class Rectangle extends Shape {
  constructor(a, b) {
    super('prostokąt');
    this.a = a;
    this.b = b;
  }

  area() {
    return this.a * this.b;
  }
}

class Square extends Rectangle {
  constructor(a) {
    super(a, a);
    this.name = 'kwadrat';
  }
}

class Circle extends Shape {
  constructor(r) {
    super('koło');
    this.r = r;
  }

  area() {
    return Math.PI * this.r * this.r;
  }
}

const shapes = [new Rectangle(3, 4), new Circle(1), new Square(5)];
for (const s of shapes) {
  console.log(s.describe());
}
const sq = shapes[2];
console.log(sq instanceof Square, sq instanceof Rectangle, sq instanceof Shape, sq instanceof Circle);

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.