Curriculum
Polymorphism is a concept in object-oriented programming that allows different objects to be treated as if they are of the same type. In Java, polymorphism can be achieved through two mechanisms: method overloading and method overriding.
Method Overloading: Method overloading allows you to define multiple methods with the same name, but with different parameters. Java can differentiate between these methods based on the number and type of arguments passed in. Here’s an example:
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } public String add(String a, String b) { return a + b; } }
In the example above, the Calculator
class has three methods called add()
. The first method takes two int
parameters and returns an int
. The second method takes two double
parameters and returns a double
. The third method takes two String
parameters and returns a String
. All three methods have the same name, but Java can differentiate between them based on the type of parameters passed in.
Method Overriding: Method overriding allows you to define a method in a subclass that has the same signature (name, return type, and parameter list) as a method in the superclass. When you call the method on an object of the subclass, the subclass’s version of the method is called instead of the superclass’s version. Here’s an example:
public class Animal { public void makeSound() { System.out.println("The animal makes a sound"); } } public class Dog extends Animal { public void makeSound() { System.out.println("The dog barks"); } } public class Cat extends Animal { public void makeSound() { System.out.println("The cat meows"); } }
In the example above, the Animal
class has a method called makeSound()
. The Dog
and Cat
classes both extend the Animal
class and override the makeSound()
method with their own implementation. When you call the makeSound()
method on an object of the Dog
class, the Dog
class’s version of the method is called, and when you call the makeSound()
method on an object of the Cat
class, the Cat
class’s version of the method is called.
Polymorphism is a powerful concept that allows you to write code that is more flexible and reusable. By treating objects as if they are of the same type, you can write code that works with a wide range of objects, without needing to know their specific types in advance.