summary refs log tree commit diff stats
path: root/java/code/RuntimePolymorphismExample.java
diff options
context:
space:
mode:
Diffstat (limited to 'java/code/RuntimePolymorphismExample.java')
-rw-r--r--java/code/RuntimePolymorphismExample.java47
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();
+    }
+}