-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdynamic_dispatch.java
More file actions
77 lines (65 loc) · 2.31 KB
/
dynamic_dispatch.java
File metadata and controls
77 lines (65 loc) · 2.31 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Abstract superclass defining common behavior for all shapes
abstract class Shape {
// Abstract method to be overridden by each specific shape subclass
public abstract double calculateArea();
// Method to display area, uses dynamic dispatch to call the correct calculateArea
public void displayArea() {
System.out.println("The area is: " + calculateArea());
}
}
// Circle class extends Shape and overrides calculateArea
class Circle extends Shape {
private double radius;
// Constructor to initialize the radius of the circle
public Circle(double radius) {
this.radius = radius;
}
// Implementation of calculateArea specific to Circle
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Square class extends Shape and overrides calculateArea
class Square extends Shape {
private double side;
// Constructor to initialize the side of the square
public Square(double side) {
this.side = side;
}
// Implementation of calculateArea specific to Square
@Override
public double calculateArea() {
return side * side;
}
}
// Triangle class extends Shape and overrides calculateArea
class Triangle extends Shape {
private double base;
private double height;
// Constructor to initialize the base and height of the triangle
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
// Implementation of calculateArea specific to Triangle
@Override
public double calculateArea() {
return 0.5 * base * height;
}
}
// Main class to demonstrate dynamic dispatch
public class dynamic_dispatch{
public static void main(String[] args) {
// Create an array of Shape references pointing to different shape objects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(5); // Circle with radius 5
shapes[1] = new Square(4); // Square with side length 4
shapes[2] = new Triangle(6, 3); // Triangle with base 6 and height 3
// Iterate through the array, invoking displayArea on each shape
for (Shape shape : shapes) {
shape.displayArea();
// Dynamic dispatch ensures the correct calculateArea method is called
}
}
}