DEV Community

jain10gunjan
jain10gunjan

Posted on

1

Polymorphism in JAVA

Polymorphism is the ability of a single object to take on multiple forms. In Java, polymorphism is implemented using inheritance, method overloading, and method overriding.

Here is an example of polymorphism using method overloading:

public 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();
int sum1 = calc.add(1, 2); // sum1 is 3
int sum2 = calc.add(1, 2, 3); // sum2 is 6

Enter fullscreen mode Exit fullscreen mode

In this example, the Calculator class has two versions of the add method: one that takes two arguments and one that takes three arguments. Both of these methods have the same name, but they have different parameter lists, so they are considered to be overloaded versions of the same method.

Here is an example of polymorphism using method overriding:

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

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

Animal animal = new Dog();
animal.makeSound(); // prints "Woof!"

Enter fullscreen mode Exit fullscreen mode

In this example, the Animal class has a makeSound method that prints a generic animal sound. The Dog class extends the Animal class and overrides the makeSound method to provide a specific implementation for dogs. When the makeSound method is called on a Dog object, the version defined in the Dog class will be used, rather than the version defined in the Animal class.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay