This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The answer can be and is very lengthy and subjective:
1. Coupling is how much does a class know about other class. Cohesion is how well focused a class is: a class having a single(single responsibility pattern) well defined purpose is said to exhibit higher degree of cohesion..
2. Given two lines of code, A and B, they are coupled when B must change behavior only because A changed.
They are cohesive when a change to A allows B to change so that both add new value.
Sathi Krishna wrote:In which real scenarios we'll implement these in our development.
Whenever you lay hands on a piece of code, the two are involved.
Cohesion refers to the degree of specific tasks a class has. You always aim for a class that has one single purpose. It does one thing, and this one thing does it well.
A class that does read files, performs database updates and on top of that displays a GUI, is considered to have lousy cohesion.
The result is lousy maintainability and reusability.
Think about it. You would need the file reading capabilities in another project. With a highly cohesive class that only handles the file handling processes, no problem.
Coupling is the degree to which one class exposes itself to another. The aim is to hide as much of the implementation details as possible. In the best case you only expose what is defined in a common interface. The worst case would be having all methods public, even the ones that will (or should) never be used by the implementer. This, again results in lousy maintainability (because you break other peoples code as soon as you change your implementation details).
JDBCSupport - An easy to use, light-weight JDBC framework -
Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of the instance variables. In general the more variables a method manipulates the more cohesive that method is to its class. A class in which each variable is used by each method is maximally cohesive.
Please note that it is neither advisable nor possible to create such maximally cohesive classes. But when cohesion is high, it means that the methods and variables of the class are co-dependent and hang together as a logical whole.
You can refer to Clean Code by Robert C.Martin for more examples on this topic.