суббота, 13 января 2024 г.

Polymorphism in Java

    Polymorphism is a concept by which we can perform a single action in different ways.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

  • Compile-time Polymorphism (Method Overloading):

  • Method overloading occurs when a class has multiple methods with the same name but different parameters (number, type, or order of parameters).
  • The compiler determines which method to call based on the number and types of arguments passed during the method invocation.

public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {
return a + b;
}
}


  • Runtime Polymorphism (Method Overriding):

  • Runtime polymorphism is achieved through method overriding. It occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
  • The overridden method in the subclass should have the same signature (name, return type, and parameters) as the method in the superclass.
  • Runtime polymorphism can't be achieved by data members.


class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}

class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}

class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}

Комментариев нет:

Отправить комментарий