Monday, November 6, 2023

Polymorphism and Open Closed Design Principle Example in Java

Java is an object-oriented programming language that allows developers to create complex software applications by organizing code into objects. One of the key features of object-oriented programming is Polymorphism. Polymorphism refers to the ability of objects to take on different forms, depending on the context in which they are used. In Java, polymorphism is achieved through two mechanisms: inheritance and interfaces. In this blog post, I will explain what polymorphism is in Java, how it works, and provide examples to illustrate its usage. We will also discuss the benefits of using polymorphism in your Java programs, as well as some best practices for implementing it effectively.


Polymorphism + Open Closed Design Principle Example in Java

Here is an example in JAva which is not using Polymorphism but structured programming. First we will see the shortcomings of this code, particularly on maintenance part as you often need to add, remove, and change memberships. 

Later we will see how can we make this code better using Polymorphism and Open Closed design principle in Java and object oriented programming

import java.util.List;


/**
 * Java Program to demonstrate Polymorphism in Object Oriented Programming
 *
 * @author Javin Paul
 */
public class PolymorphismDemo{

      public static void main(String args[]) {
            Member m = new Member();
            System.out.println(m.discount(Member.YEARLY));
      }
   
      public static getBilledAmount(int amount){
         
      }

}

And, now let's see our Membership class which can be make better using Polymorphism. Every time you need to add a new membership, you need to modify discount code and this, class, which is more error prone than adding a new class. 

This is also  known as Open-Closed design principle. It means open for  extension but closed for modification and also encourage you to add new functionality, we add new code.
/*
* A Membership class
*/

class MemberShip {
      public static final int MONTHLY = 1;
      public static final int YEARLY = 2;
      public static final int LIFETIME = 3;
      private static final int NO_DISCOUNT = 0;

      private int type;
   
      public MemberShip(int type){
            this.type = type;
      }
   
      public int discount() {
            int discount = NO_DISCOUNT;
            switch (type) {
            case MONTHLY:
                  discount = 1;
                  break;
            case YEARLY:
                  discount = 2;
                  break;
            case LIFETIME:
                  discount = 3;
                  break;
            default:
                  discount = 0;
            }
            return discount;
      }
}


This a Java program that calculates a discount based on the type of membership. It uses a switch-case statement to determine the discount percentage for different membership types (MONTHLY, YEARLY, and LIFETIME). 

The program demonstrates a lack of polymorphism because it relies on a switch statement to handle different membership types, making it less extensible when new membership types are introduced.

Let's improve this code by using polymorphism to achieve a more extensible and maintainable design:

public class PolymorphismDemo {

    public static void main(String args[]) {
        MemberShip monthlyMember = new MonthlyMember();
        MemberShip yearlyMember = new YearlyMember();

        System.out.println(monthlyMember.discount()); // Output: 1
        System.out.println(yearlyMember.discount());  // Output: 2
    }
}

abstract class MemberShip {
    public abstract int discount();
}

class MonthlyMember extends MemberShip {
    @Override
    public int discount() {
        return 1;
    }
}

class YearlyMember extends MemberShip {
    @Override
    public int discount() {
        return 2;
    }
}

Here is also a nice UML diagram which explains how easy it will be to add membership types can be added easily by creating new classes that extend MemberShip.

Polymorphism and Open Closed Design Principle Example in Java



In this improved version

We create an abstract MemberShip class with an abstract discount method. This forms the basis for different membership types to implement their own discount calculation logic.

We create concrete classes like MonthlyMember and YearlyMember, each extending the MemberShip class. These classes override the discount method to provide specific discount values for their respective membership types.

In the main method, we create instances of MonthlyMember and YearlyMember and call the discount method on each instance. This demonstrates polymorphism because the appropriate discount method for each membership type is called at runtime.

By using polymorphism and following the Open-Closed design principle, this code becomes more extensible. Adding new membership types is as simple as creating a new class that extends MemberShip and providing the specific discount calculation logic in that class. This approach makes the code easier to maintain and less error-prone when new functionality is added.


That's all about this example of Polymorphism in Java. You an see that how useful Polymorphism is. It is actually one of the key Object oriented fundamentals along with Abstraction, Encapsulation, and Inheritance and every programmer should learn about it. 

You can use Polymorphism to write code which behave differently on runtime. It gives a lot of flexibility to your program and you can also use to simplify complex if-else and switch statement. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.