blob: b702ca738ee92a1396e781a13ff92fbab1e0bf73 (
plain) (
blame)
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
|
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
public void calculateArea() {
System.out.println("Calculating Circle Area");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
public void calculateArea() {
System.out.println("Calculating Square Area");
}
}
public class RuntimePolymorphismExample {
public static void main(String[] args) {
// Creating objects of the subclasses
Shape circle = new Circle();
Shape square = new Square();
// Demonstrate runtime polymorphism
// The draw() method of the appropriate subclass will be called dynamically
circle.draw();
square.draw();
// Uncommenting the lines below will result in a compilation error
// since the calculateArea() method is not part of the Shape interface
// circle.calculateArea();
// square.calculateArea();
// However, calculateArea() method can still be called if it is casted to the specific subclass
((Circle) circle).calculateArea();
((Square) square).calculateArea();
}
}
|