Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (attributes) and methods (functions) that operate on that data within a single unit or class. It restricts direct access to some of an object's components, which helps to protect the integrity of the data and prevent unintended interference. By using access modifiers (like private, public, and protected), encapsulation promotes modularity and enhances code maintainability. This principle allows developers to expose only the necessary parts of an object while hiding its internal workings.
Usually there is an LED and a photo transistor, embedded in the same component. The package is usually a DIL with either 6 pins or four, for single devices. The idea is, that a signal is sent to the LED and picked up with the transistor, held in a sealed encapulation. The only connection between the two is LIGHT, no other electrical connection. So it prodides ultimate isolation to prevent stray voltages getting into sensitive areas. They are used in switched mode power supplies, to provide a feed back signal between the Low voltage side and the high voltage side. They are also used in home telephones, to send the 50vac ring signal to the electronic warbler circuit. To isolate the user from any high voltage. (I have known phones suffering lightning strikes, to have the top blown off the OptoIsolator!).
The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much. If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that? • Keep instance variables protected (with an access modifier, mostly private). • Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable. • For the methods, use the JavaBeans naming convention of set and get. source- SCJP book by Kathy and Bert