Polymorphism in Java | Method Overloading & Method Overriding






 In Java, polymorphism refers to the ability of a single variable, function or object to take on multiple forms.


There are two types of polymorphism in Java: 

1. Compile-time polymorphism (Method Overloading)

2. Runtime polymorphism. (Method Overriding)



1. Compile-time polymorphism (also known as "Method Overloading") occurs when multiple methods in a class have the same name but different parameters. 


For example:


class PolyExample {
 
  public void print(int x) {
 
    System.out.println(x);
 
  }
 
  public void print(String s) {
 
    System.out.println(s);
 
  }
 
}



In this example, the class "PolyExample" has two methods named "print", one that takes an integer as a parameter and one that takes a string. 

During compilation, the Java compiler will determine which "print" method to call based on the type of parameter passed.





2. Runtime polymorphism (also known as "Method Overriding") occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.


 For example:


class Animal {
 
  public void makeSound() {
 
    System.out.println("Some generic animal sound");
 
  }
 
}
class Dog extends Animal {
 
  @Override
 
  public void makeSound() {
 
    System.out.println("Woof woof");
 
  }
 
}


In this example, the "Animal" class has a method named "makeSound", and the "Dog" class extends "Animal" and provides its own implementation of the "makeSound" method. During runtime, when an object of the "Dog" class calls the "makeSound" method, the specific implementation provided by the "Dog" class will be executed.



There's also another type of polymorphism called coercion polymorphism, which is when a value or an object of one type is automatically converted to another type without any explicit type casting.


You can use polymorphism to write code that is more flexible, reusable, and easier to maintain, by using the same method or function name but with different implementations depending on the context.




Post a Comment

Post a Comment (0)

Previous Post Next Post