DEV Community

Cover image for What is Polymorphism in Java?
Kudzai Murimi
Kudzai Murimi

Posted on

8 1 1 1 1

What is Polymorphism in Java?

Polymorphism might sound like a complicated term, but it’s a simple and powerful concept in Java that makes your code more flexible and easier to maintain. This guide will help you understand what polymorphism is, how it works in Java, and where you can use it, all with clear examples and simple language.

What is Polymorphism?

Polymorphism is a concept in object-oriented programming that allows a single method, class, or object to behave in different ways based on the context. The word polymorphism comes from Greek, meaning “many forms.”

In Java, polymorphism enables you to write code that can work with objects of different types using a common interface or parent class.

Think of a universal remote control. It can work with different devices—TVs, DVD players, and sound systems. Similarly, polymorphism allows a method or object to interact with different types of objects in a consistent way.

Types of Polymorphism in Java

In Java, there are two main types of polymorphism:

  1. Compile-Time Polymorphism (Static Polymorphism) This type is achieved through method overloading. It happens when a class has multiple methods with the same name but different parameter lists. The method to be called is determined at compile time.

Example:

   class Calculator {
       // Add two integers
       int add(int a, int b) {
           return a + b;
       }

       // Add three integers
       int add(int a, int b, int c) {
           return a + b + c;
       }
   }

   public class Main {
       public static void main(String[] args) {
           Calculator calc = new Calculator();
           System.out.println(calc.add(2, 3));       // Outputs: 5
           System.out.println(calc.add(2, 3, 4));   // Outputs: 9
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Run-Time Polymorphism (Dynamic Polymorphism) This type is achieved through method overriding, where a subclass provides a specific implementation of a method already defined in its parent class. The method to be executed is determined at runtime based on the object type.

Example:

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

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

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

   public class Main {
       public static void main(String[] args) {
           Animal myAnimal;

           myAnimal = new Dog();
           myAnimal.sound();  // Outputs: Bark

           myAnimal = new Cat();
           myAnimal.sound();  // Outputs: Meow
       }
   }
Enter fullscreen mode Exit fullscreen mode

Why is Polymorphism Useful?

Polymorphism makes your code:

  1. Flexible: You can write code that works with different types of objects.
  2. Reusable: Common functionality can be reused across different classes.
  3. Maintainable: Changes in one part of the code (e.g., a subclass) don’t require changes in other parts.

Where Can Polymorphism Be Applied?

  1. Designing User Interfaces: A single interface can work for different button types or widgets.
  2. Game Development: A base Character class can represent different types of characters like Hero, Enemy, or NPC.
  3. Database Connections: A Database interface can handle different database types like MySQL, PostgreSQL, or MongoDB.

Learn More About Polymorphism in Java

If you’re eager to dive deeper, here are some resources to check out:

  1. https://www.youtube.com/watch?v=jhDUxynEQRI&pp=ygUJI2FtYW55b29w
  2. Oracle’s Official Java Documentation
  3. Java Programming Tutorial on W3Schools
  4. GeeksforGeeks Polymorphism Article

Do you have additional examples or resources for understanding polymorphism in Java? Feel free to share them! Let’s make learning Java a collaborative experience.

Polymorphism might seem tricky at first, but it’s one of the most useful tools in Java. Whether you’re writing reusable code, building flexible applications, or designing scalable systems, understanding polymorphism will help you become a better programmer. Try out the examples and see for yourself how powerful this concept can be!

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 (2)

Collapse
 
omarafandi profile image
Omar

i learn'd polymorphism in java then i forget, but this post rememorized me, thanks

Collapse
 
respect17 profile image
Kudzai Murimi

Happy that you found it helpful

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

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

Okay