|
| 1 | +// Wrong way |
| 2 | +class Bird { |
| 3 | + fly(): void { |
| 4 | + console.log('Flying!'); |
| 5 | + } |
| 6 | +} |
| 7 | + |
| 8 | +class Penguin extends Bird { |
| 9 | + fly(): void { |
| 10 | + throw new Error('Penguins cannot fly!'); |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +function makeBirdFly(bird: Bird): void { |
| 15 | + bird.fly(); |
| 16 | +} |
| 17 | + |
| 18 | +const bird = new Bird(); |
| 19 | +const penguin = new Penguin(); |
| 20 | + |
| 21 | +makeBirdFly(bird); |
| 22 | +// makeBirdFly(penguin); // Not working // |
| 23 | + |
| 24 | +// Correct way |
| 25 | +class Bird2 { |
| 26 | + eat(): void { |
| 27 | + console.log('Eating...'); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class FlyingBird extends Bird2 { |
| 32 | + fly(): void { |
| 33 | + console.log('Flying!'); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class Penguin2 extends Bird2 { |
| 38 | + swim(): void { |
| 39 | + console.log('Swimming!'); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +function makeFlyingBirdFly(bird: FlyingBird): void { |
| 44 | + bird.fly(); |
| 45 | +} |
| 46 | + |
| 47 | +const eagle = new FlyingBird(); |
| 48 | +const penguin2 = new Penguin2(); |
| 49 | + |
| 50 | +makeFlyingBirdFly(eagle); |
| 51 | +// makeFlyingBirdFly(penguin2); // Not working // |
| 52 | + |
| 53 | +// ** Extra Exercise ** // |
| 54 | +abstract class Vehicle { |
| 55 | + abstract accelerate(): void; |
| 56 | + abstract brake(): void; |
| 57 | +} |
| 58 | + |
| 59 | +class Car extends Vehicle { |
| 60 | + accelerate(): void { |
| 61 | + console.log('Car is accelerating'); |
| 62 | + } |
| 63 | + |
| 64 | + brake(): void { |
| 65 | + console.log('Car is braking'); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +class Motorcycle extends Vehicle { |
| 70 | + accelerate(): void { |
| 71 | + console.log('Motorcycle is accelerating'); |
| 72 | + } |
| 73 | + |
| 74 | + brake(): void { |
| 75 | + console.log('Motorcycle is braking'); |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +class Bicycle extends Vehicle { |
| 80 | + accelerate(): void { |
| 81 | + console.log('Bicycle is accelerating'); |
| 82 | + } |
| 83 | + |
| 84 | + brake(): void { |
| 85 | + console.log('Bicycle is braking'); |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +function testVehicle(vehicle: Vehicle): void { |
| 90 | + vehicle.accelerate(); |
| 91 | + vehicle.brake(); |
| 92 | +} |
| 93 | + |
| 94 | +const car = new Car(); |
| 95 | +const motorcycle = new Motorcycle(); |
| 96 | +const bicycle = new Bicycle(); |
| 97 | + |
| 98 | +testVehicle(car); |
| 99 | +testVehicle(motorcycle); |
| 100 | +testVehicle(bicycle); |
0 commit comments