diff options
author | Sudipto Mallick <smlckz@termux-alpine> | 2024-01-25 05:50:05 +0000 |
---|---|---|
committer | Sudipto Mallick <smlckz@termux-alpine> | 2024-01-25 05:50:05 +0000 |
commit | 13f9553a26a51b95ab194e5328ad302b35d7b118 (patch) | |
tree | 8cc94ea3ae2baac3335bd8471196f90a28a2a066 /java/code/RuntimePolymorphismExample.java | |
parent | a5afdcfa7165e100042f03de1b3f7a601389776f (diff) | |
download | zadania-13f9553a26a51b95ab194e5328ad302b35d7b118.tar.gz |
Complete Java assignments
Diffstat (limited to 'java/code/RuntimePolymorphismExample.java')
-rw-r--r-- | java/code/RuntimePolymorphismExample.java | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/java/code/RuntimePolymorphismExample.java b/java/code/RuntimePolymorphismExample.java new file mode 100644 index 0000000..b702ca7 --- /dev/null +++ b/java/code/RuntimePolymorphismExample.java @@ -0,0 +1,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(); + } +} |