Javatpoint Logo
Javatpoint Logo

Cohesion in Java

In this section, we will discuss about cohesion in Java. Cohesion defines how the classes in Java are designed. Cohesion in Java is the principle of Object-Oriented programming. Cohesion is closely related to ensuring that the purpose for which a class is getting created in Java is well-focused and single. In other words, the more closely related stuff is grouped in a class, the higher will be the cohesiveness.

For better understanding, consider the following example.

FileName: CohesiveExample.java

Output:

Addition of the numbers 9 and 46 is: 55
t is not a vowel.
o is a vowel.

Explanation: The above example is straightforward to understand. There is a class that contains two methods. One method is doing the addition of two numbers (an arithmetic operation), and another method focuses on vowel and consonants (related to English alphabets). However, no one can give a clear reason why these two methods are clubbed together in a single class as there is no relation between vowels or consonants and numbers. Therefore, we can say that cohesiveness is missing in the class.

Need of Cohesiveness

One obvious question is why we need cohesiveness? We need cohesiveness because it is easy to work in a highly cohesive structure. The update and modification in the code become easy. Think about how books are arranged in a library. In a library, we do the categorization of stuff. There is a separate section for each of the different subjects.

For example, books of biology are placed together, and books of mathematics are placed together. In a library, we do not shuffle books of mathematics and biology. Because it becomes difficult to find a mathematics or biology book. Similarly, we do the categorization of stuff in the programming world also. Shuffling of unrelated stuff is avoided in the code. In fact, it is impossible to work on a code where cohesiveness within the class is ignored.

Therefore, we need to modify the above-written code in such a way that it adheres to the principle of cohesiveness. The modified version of the above code is mentioned below.

FileName: CohesiveExample1.java

Output:

Addition of the numbers 9 and 46 is: 55
t is not a vowel.
o is a vowel.

Explanation: The above code provides two separate classes: one for doing the addition operation and another for doing the character operation. It is done because character and addition operations are not related to each other. Thus, cohesiveness in the above program is maintained.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA