Understanding Dynamic and Static Polymorphism in Java
Polymorphism in Java allows objects of different classes to behave in a similar manner, despite their differences. This flexibility is achieved through two types of polymorphism: dynamic and static.
Dynamic Polymorphism
Also known as runtime polymorphism, dynamic polymorphism occurs when a method override in subclasses takes place. The call to the overriding method is resolved at runtime based on the actual object type.
Consider the following example:
<code class="java">class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { @Override public void move() { System.out.println("Dogs can walk and run"); } } public class Main { public static void main(String[] args) { Animal animal = new Animal(); // Animal reference and object Animal dog = new Dog(); // Animal reference but Dog object animal.move(); // Output: Animals can move dog.move(); // Output: Dogs can walk and run } }</code>
In this example, the move() method is overridden in the Dog class. When the animal reference calls the move() method, the actual type of the object (Animal or Dog) determines the behavior at runtime. This is dynamic polymorphism.
Static Polymorphism (Method Overloading)
Static polymorphism, also called compile-time polymorphism, occurs when multiple methods with the same name but different parameter lists exist within the same class. The call to the correct method is determined at compile time based on the number and types of the arguments passed.
Consider the following example:
<code class="java">class Calculation { void sum(int a, int b) { System.out.println(a + b); } void sum(int a, int b, int c) { System.out.println(a + b + c); } public static void main(String[] args) { Calculation calculation = new Calculation(); calculation.sum(10, 10, 10); // Output: 30 calculation.sum(20, 20); // Output: 40 } }</code>
In this example, the sum() method is overloaded with different parameter lists. The call to the correct sum() method is determined at compile time based on the number of arguments passed. This is static polymorphism or method overloading.
The above is the detailed content of What is the difference between dynamic and static polymorphism in Java?. For more information, please follow other related articles on the PHP Chinese website!