DEV Community

Karthick M
Karthick M

Posted on

Polimorphism

Types of Polimorphism:
1.Method overriding or runtime polymorphism.
2.Method overloading or compile-time polymorphism.

  • Method overriding: Method overriding means defining a method in the child class with the same name, same parameters, and same return type as the method in the parent class.

It is used to provide a specific implementation in the child class.
1.Rules for Method Overriding
2.Method name must be same
3.Parameters must be same
4.Return type must be same
5.Must have inheritance (extends)
6.Happens between parent and child class

Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {
@override
void sound() {
System.out.println("Dog barks");
}
}

public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}

  • Method overloading: Method overloading means creating multiple methods with the same name in the same class, but with different parameters.

Why we use Method Overloading?

  • Improves code readability
  • Same method name for similar operations
  • No need to create different method names

Rules for Method Overloading:
Methods must differ in at least one of these:
1.Number of parameters
2.Type of parameters
3.Order of parameters

Example:
class Calculator {

void add(int a, int b) {
    System.out.println(a + b);
}

void add(int a, int b, int c) {
    System.out.println(a + b + c);
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
c.add(10, 20); // calls first method
c.add(10, 20, 30); // calls second method
}
}

Top comments (0)