Sunday, January 8, 2012

Encapsulation

At this point we can introduce another bit of jargon you can use to impress or bore your friends - encapsulation. Encapsulation refers to the hiding of items of data and methods within an object. This is achieved by specifying them as private in the definition of the class. In the CowboyHat class, the instance variables owner, type, size, and hatOn were encapsulated. They were accessible only through the methods defined for the class. Therefore, the only way to alter the values they contain is to call a method that does that. Being able to encapsulate members of a class in this way is important for the security and integrity of class objects. You may have a class with data members that can take on only particular values. By hiding the data members and forcing the use of a method to set or change the values, you can ensure that only legal values are set.

I mentioned earlier another major advantage of encapsulation - the ability to hide the implementation of a class. By allowing only limited access to the members of a class, you have the freedom to change the internals of the class without necessitating changes to Java programs that use the class. As long as the external characteristics of the methods that can be called from outside the class remain unchanged, the internal code can be changed in any way that you, the programmer, want.

A particular object, an instance of CowboyHat, incorporates, or encapsulates, the owner, the size of the object, and the status of the hat in the instance variable hatOn. Only the constructor, and the putHatOn(), takeHatOff(), changeOwner(), and getSize() methods can be accessed externally.

No comments:

Post a Comment

Thanks for Commenting......