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?
5 Answers
0
It only works if there is created an object of the subclass where the overrided method exist.
0
if subclass SubC is downcasted:
C c = new SubC();
c.method();
âą is C.method() overrided ?
yes - use SubC.method()
no - use C.method()
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/
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
}
}
0
java doesn't have the keyword "virtual"