Nov 12, 2010

Encapsulation, Loose coupling and HAS-A relation ship in Java

Encapsulation in an OOP sense generally aims to guide (or force) users of your components to use your classes correctly and makes it harder to abuse the class's functionality by hiding the implementation. Encapsulation allows an object to separate its interface from its implementation. The data and the implementation code for the object are hidden behind its interface. For example, in Java, we have pre defined libraries, and we use them, but, we don't know how does the internal implementation of a Class. We simply use the public method as the interface to access the object.

"Loose coupling" is not a coding issue, it's a design issue. Loose coupling simply means that individual design elements should be constructed so the amount of unnecessary information they need to know about other design elements are reduced. In short, loose coupling is a design goal that seeks to reduce the interdependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.





The degree of coupling between two components can be qualitatively measured by determining the effects of changing the contract or interface between two components or systems. For example:

* What would happen if you added or deleted a property from a class?
* What would happen if you changed the data type of a column in a table?
* What would happen if you added a column to a table?
* What would happen if you changed you asynchronous email component?
* What would happen if your database server changed from SQL Server to mySQL or Oracle?


The degree of pain that each of these changes would cause you is a good qualitative measurement of how tightly coupled your components are to the components they depend on.

interface Bounceable {}

class Car implements Bounceable {}
class Ball implements Bounceable {}

public class TestCoupling {
 Car c;// tight coupling
 Bounceable b; // loose coupling.
}

With the Bounceable reference, we can have a Car instance or a Ball instance. So, the TestCoupling and the Car or Ball are loosely coupled(without the Car reference).
Post a Comment