🧬 Dziedziczenie
Klasy mogą dziedziczyć z innych klas używając operatora <.
Podstawowe dziedziczenie
class Animal {
init(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound";
}
}
class Dog < Animal {
init(name, breed) {
super.init(name);
this.breed = breed;
}
speak() {
return this.name + " barks!";
}
}
let dog = Dog("Burek", "Labrador");
print(dog.speak());
print(dog.breed);
super
class Cat < Animal {
init(name, color) {
super.init(name);
this.color = color;
}
speak() {
let base = super.speak();
return base + " (meow!)";
}
}
Łańcuch dziedziczenia
class Vehicle {
init(brand) { this.brand = brand; }
start() { return "Starting..."; }
}
class Car < Vehicle {
init(brand, model) {
super.init(brand);
this.model = model;
}
honk() { return "Beep!"; }
}
class SportsCar < Car {
init(brand, model, topSpeed) {
super.init(brand, model);
this.topSpeed = topSpeed;
}
race() { return "Vroom!"; }
}
let car = SportsCar("Ferrari", "F40", 320);
print(car.start());
print(car.honk());
print(car.race());