Distinguishing Dynamic and Static Polymorphism in Java
Understanding the difference between dynamic and static polymorphism is crucial in object-oriented programming with Java. This article will provide a simplified explanation and example to elucidate this concept.
Dynamic vs. Static Polymorphism
Polymorphism allows a single method name to have multiple implementations depending on the object type calling it. There are two primary types of polymorphism:
Method Overloading
Method overloading is a form of static polymorphism where multiple methods with the same name exist in the same class but differ in their parameters. When calling an overloaded method, Java determines the appropriate method to invoke based on the number and types of arguments passed in.
Code Example (Method Overloading):
<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 obj = new Calculation(); obj.sum(10, 10, 10); // Output: 30 obj.sum(20, 20); // Output: 40 } }</code>
Method Overriding
Method overriding is a form of dynamic polymorphism where methods with the same name and signature are declared in different classes but share a common parent class. When calling an overridden method, Java determines the method to invoke based on the object's actual class at runtime.
Code Example (Method Overriding):
<code class="java">class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String[] args) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // Output: Animals can move b.move(); // Output: Dogs can walk and run } }</code>
The above is the detailed content of How do Method Overriding and Method Overloading Differ in Java?. For more information, please follow other related articles on the PHP Chinese website!