-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorphism.java
More file actions
94 lines (72 loc) · 2.08 KB
/
Copy pathPolymorphism.java
File metadata and controls
94 lines (72 loc) · 2.08 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package oop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Polymorphism: a parent type reference can point to child objects,
and the executed method depends on the actual object type (dynamic dispatch).
*/
// Base class (superclass)
class Shape {
// Abstract method: Every subclass MUST implement it
double calculateArea() {
return 0.0;
}
// Concrete method: Shared by all subclasses
String name() {
return "Generic shape";
}
}
// Derived class (subclass) that inherits from Shape
class Circle extends Shape {
// Constructor that calls the superclass constructor
double radius;
Circle(double radius) {
this.radius = radius;
}
// Overriding the abstract method from the superclass
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
// Overriding the concrete method from the superclass
@Override
String name() {
return "Circle";
}
}
// Derived class (subclass) that inherits from Shape
class Rectangle extends Shape {
// Constructor that calls the superclass constructor
double base;
double height;
Rectangle(double base, double height) {
this.base = base;
this.height = height;
}
// Overriding the abstract method from the superclass
@Override
double calculateArea() {
return base * height;
}
// Overriding the concrete method from the superclass
@Override
String name() {
return "Rectangle";
}
}
public class Polymorphism {
private static final Logger logger = LoggerFactory.getLogger(Polymorphism.class);
public static void main() {
// Array of type Shape containing different concrete objects
Shape[] shapes = {
new Circle(3),
new Rectangle(4, 5)
};
// The correct method is called based on the ACTUAL type of the object
for (Shape f : shapes) {
if (logger.isInfoEnabled()) {
logger.info("{} -> area: {}", f.name(), f.calculateArea());
}
}
}
}