Polymorphism with Examples

Polymorphism is a concept in programming that allows an object to take on many forms. In Java, there are two types of polymorphism: compile-time polymorphism (or method overloading) and runtime polymorphism (or method overriding).

Compile-time polymorphism is achieved by having multiple methods with the same name but different parameters in the same class. When a method is called, the compiler determines which method to execute based on the number and data types of the arguments provided. Method overloading allows for more flexibility in method naming and can improve code readability.

Here is an example of method overloading:

csharp
class Calculator { public int add(int x, int y) { return x + y; } public int add(int x, int y, int z) { return x + y + z; } } Calculator calc = new Calculator(); System.out.println(calc.add(1, 2)); // outputs 3 System.out.println(calc.add(1, 2, 3)); // outputs 6

In the above example, there are two methods with the same name "add", but they take different numbers of arguments. The first method takes two integers and returns their sum, while the second method takes three integers and returns their sum.

Runtime polymorphism is achieved by having methods in the parent class and child class with the same name and signature. When a method is called on an object of the child class, the JVM determines which method to execute based on the type of the object at runtime. This allows for more flexibility in method implementation and can improve code reusability.

Here is an example of method overriding:

java
class Animal { public void speak() { System.out.println("Animal speaks"); } } class Cat extends Animal { @Override public void speak() { System.out.println("Meow!"); } } Animal animal = new Animal(); animal.speak(); // outputs "Animal speaks" Cat cat = new Cat(); cat.speak(); // outputs "Meow!" Animal animal2 = new Cat(); animal2.speak(); // outputs "Meow!" (runtime polymorphism)

In the above example, there are two classes: Animal and Cat. Cat is a subclass of Animal, and it overrides the speak() method of its parent class. When a method is called on an object of the Cat class, the overridden speak() method is called instead of the one in the Animal class. When a method is called on an object of the Animal class that is actually an instance of the Cat class (as in the last line), the overridden speak() method of the Cat class is called due to runtime polymorphism.

Previous Post Next Post