REAL-TIME Use of Polymorphism

Hi Everyone,

In a recent interview, I encountered an interesting question related to Java OOP (Object-Oriented Programming) concepts.

As OOP concepts are crucial from an interview perspective, especially when working with languages like Java, C#, and many others, it's important to have a solid understanding and hands-on experience with them.

The interviewer asked me to explain a REAL-TIME use of polymorphism that I had applied in one of my projects or applications.

I’d like to share two examples of real-time uses of polymorphism: -

Database Operations - DAO Pattern:

If you’re using different databases or have different data access mechanisms (e.g., MySQL, MongoDB, etc.), polymorphism can help by abstracting database operations behind a common interface.

public interface Database {
    void insert(String data);
}

public class MySQLDatabase implements Database {
    public void insert(String data) {
        System.out.println("Inserting into MySQL: " + data);
    }
}

public class MongoDBDatabase implements Database {
    public void insert(String data) {
        System.out.println("Inserting into MongoDB: " + data);
    }
}        

Web Development - Request Handlers:

In web applications, different HTTP requests (GET, POST, PUT, DELETE) can be processed using polymorphism.

public class RequestHandler {
    public void handle(Request request) {
        // Generic request handling logic
    }
}

public class GetRequestHandler extends RequestHandler {
    public void handle(Request request) {
        // Logic for handling GET requests
    }
}

public class PostRequestHandler extends RequestHandler {
    public void handle(Request request) {
        // Logic for handling POST requests
    }
}        

To view or add a comment, sign in

More articles by Tushar Kumar

Explore content categories