Skip to content

Commit cb90521

Browse files
committed
#28 - JavaScript
1 parent 5ce1ffb commit cb90521

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Wrong way
2+
class Bird {
3+
fly() {
4+
console.log('Flying!');
5+
}
6+
}
7+
8+
class Penguin extends Bird {
9+
fly() {
10+
throw new Error('Penguins cannot fly!');
11+
}
12+
}
13+
14+
function makeBirdFly(bird) {
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() {
27+
console.log('Eating...');
28+
}
29+
}
30+
31+
class FlyingBird extends Bird2 {
32+
fly() {
33+
console.log('Flying!');
34+
}
35+
}
36+
37+
class Penguin2 extends Bird2 {
38+
swin() {
39+
console.log('Swimming!');
40+
}
41+
}
42+
43+
function makeFlyingBirdFly(bird) {
44+
bird.fly();
45+
}
46+
47+
const eagle = new FlyingBird();
48+
const penguin2 = new Penguin2();
49+
50+
makeFlyingBirdFly(eagle);
51+
// makeBirdFly(penguin); // Not working //
52+
53+
// Extra Exercise //
54+
class Vehicle {
55+
accelerate() {
56+
throw new Error('accelerate() must be implemented');
57+
}
58+
59+
brake() {
60+
throw new Error('brake() must be implemented');
61+
}
62+
}
63+
64+
class Car extends Vehicle {
65+
accelerate() {
66+
console.log('Car is accelerating');
67+
}
68+
69+
brake() {
70+
console.log('Car is braking');
71+
}
72+
}
73+
74+
class Motorcycle extends Vehicle {
75+
accelerate() {
76+
console.log('Motorcycle is accelerating');
77+
}
78+
79+
brake() {
80+
console.log('Motorcycle is braking');
81+
}
82+
}
83+
84+
class Bicycle extends Vehicle {
85+
accelerate() {
86+
console.log('Bicycle is accelerating');
87+
}
88+
89+
brake() {
90+
console.log('Bicycle is braking');
91+
}
92+
}
93+
94+
function testVehicle(vehicle) {
95+
vehicle.accelerate();
96+
vehicle.brake();
97+
}
98+
99+
const car = new Car();
100+
const motorcycle = new Motorcycle();
101+
const bicycle = new Bicycle();
102+
103+
testVehicle(car);
104+
testVehicle(motorcycle);
105+
testVehicle(bicycle);

0 commit comments

Comments
 (0)