What is cohesion in Java & it’s Types with Examples

Cohesion is an object orient approach of java programming which is basically deals with designing of class.

Good designing of class refer to high cohesion while bad design refer low cohesion.

Types of Cohesion

  • Low Cohesion (Bad Programming Design).

When the design of the class is not good means when class is not easy to update, retrieve & use than class is said to be Low Cohesion. In low cohesion so many method is used in one class. Low cohesion leads to less usability of code.

  • High Cohesion (Good Programming Design).

When the design of the class is good means when class is easy to update, retrieve & use than class is said to be High Cohesion. In high cohesion single method is used in one class. High cohesion leads to more usability of code.

Cohesion in java

Explanation: In the above image, you can see that in low cohesion so many methods is used inside single class which result less usability of class where in high cohesion every new class is introduce for every method which result high usability of code.

Program for high Cohesion class

class Multiply {
                 int x = 10;
                 int y = 10;
                 public int mul(int a, int b)
                 {
                    this.x = x;
                    this.y = y;
                    return x * y;
                 }
 }
 class Display 
{
  public static void main(String[] args)
    {
      Multiply m = new Multiply();
      System.out.println(m.mul(10, 10));
   }
 } 

Output

100

Leave a Reply