-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram-5.js
56 lines (48 loc) · 1.46 KB
/
program-5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Write a JavaScript program that creates a class called 'Shape' with a method to calculate the area. Create two subclasses, 'Circle' and 'Triangle', that inherit from the 'Shape' class and override the area calculation method. Create an instance of the 'Circle' class and calculate its area. Similarly, do the same for the 'Triangle' class.
class Shape {
constructor() {
this.name = "Generic Shape";
}
// Default area calculation for a generic shape
calculateArea() {
return 0;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.name = "Circle";
this.radius = radius;
}
// Overriding the area calculation method for circles
calculateArea() {
return Math.PI * this.radius * this.radius;
}
}
class Triangle extends Shape {
constructor(base, height) {
super();
this.name = "Triangle";
this.base = base;
this.height = height;
}
// Overriding the area calculation method for triangles
calculateArea() {
return 0.5 * this.base * this.height;
}
}
// Creating instances and calculating areas
const circle = new Circle(5);
const circleArea = circle.calculateArea();
console.log(
`Area of the ${circle.name} with radius ${
circle.radius
}: ${circleArea.toFixed(2)}`
);
const triangle = new Triangle(8, 10);
const triangleArea = triangle.calculateArea();
console.log(
`Area of the ${triangle.name} with base ${triangle.base} and height ${
triangle.height
}: ${triangleArea.toFixed(2)}`
);