0

What is runtime polymorphism in Java?

Can someone explain what runtime polymorphism is in Java? How does it work when a subclass overrides a method? How does the JVM decide which method to call at runtime?

11th Dec 2024, 7:42 AM
lisilo
5 Answers
0
It only works if there is created an object of the subclass where the overrided method exist.
11th Dec 2024, 9:07 AM
Jan
Jan - avatar
0
if subclass SubC is downcasted: C c = new SubC(); c.method(); ‱ is C.method() overrided ? yes - use SubC.method() no - use C.method()
12th Dec 2024, 12:12 AM
zemiak
0
I have read a blog about runtime polymorphism in Java, which explains that it allows a method to behave differently based on the object it is invoked on, determined at runtime. This is accomplished through method overriding in Java. If you're interested in learning more, I suggest you read this blog: https://uncodemy.com/blog/virtual-function-in-java-run-time-polymorphism-in-java/
12th Dec 2024, 10:08 AM
archi jain
archi jain - avatar
0
// Parent class: Shape class Shape { void draw() { System.out.println("Drawing a shape"); } } // Subclass 1: Circle class Circle extends Shape { @Override void draw() { System.out.println("Drawing a Circle"); } } // Subclass 2: Rectangle class Rectangle extends Shape { @Override void draw() { System.out.println("Drawing a Rectangle"); } } public class Main { public static void main(String[] args) { // Reference of type Shape, but object of type Circle Shape myShape = new Circle(); myShape.draw(); // Calls Circle's draw() method at runtime // Reference of type Shape, but object of type Rectangle myShape = new Rectangle(); myShape.draw(); // Calls Rectangle's draw() method at runtime } }
13th Dec 2024, 4:40 AM
Karthikeyan
Karthikeyan - avatar
0
java doesn't have the keyword "virtual"
13th Dec 2024, 8:19 PM
zemiak