Polymorphism is one of the key principles of object-oriented programming, which allows you to use a single interface to represent multiple types of objects. In Java, you can achieve polymorphism using method overloading and method overriding.
Here are some examples of using polymorphism in Java:
Method Overloading Example
In this example, we're creating a Calculator class with two add() methods that have the same name but different parameter types. This is an example of method overloading. When you call the add() method with integer arguments, the first add() method is executed. When you call the add() method with double arguments, the second add() method is executed. This allows you to reuse the same method name and provide different implementations for different parameter types.
Method Overriding Example
In this example, we're creating a Animal class with a makeSound() method that prints a message to the console. We're also creating two subclasses Dog and Cat that override the makeSound() method with their own implementation.
In the Main class, we're creating two objects animal1 and animal2 of type Animal, but their actual type is Dog and Cat respectively. We're using polymorphism to call the makeSound() method on each object, which calls the implementation defined in the respective subclass. This allows us to reuse the same method name but provide different implementations for different types of animals.
By using polymorphism, we're able to write more flexible and reusable code that can handle objects of different types without needing to know their specific types at compile time.