Polymorphism is a fundamental concept in object-oriented programming (OOP) and refers to the ability of an object to take on many forms. In Java, polymorphism is achieved through method overloading and method overriding.
Method overloading allows multiple methods to have the same name but with different parameters. When a method is called, Java determines which version of the process to execute based on the number and types of arguments passed to it.
Here is an example of method overloading in Java:
public class MyClass {
public void myMethod(int num) {
System.out.println("This is an integer: " + num);
}
public void myMethod(String str) {
System.out.println("This is a string: " + str);
}
public void myMethod(double dbl) {
System.out.println("This is a double: " + dbl);
}
}
In this example, the `myMethod` method is overloaded three times with different parameter types. When called, the appropriate version of the method is executed based on the argument passed.
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows the subclass to inherit the methods of the superclass while still being able to customize their behavior.