This class Student has bundled the data (Student_Id and name) and the methods to read and set values for these members into a single unit. In the above program, we declare a class which is the encapsulation unit. ("Student Data:" "\nStudent ID:" s.getId() getters, setters for Student_Id and name fields. Java Encapsulation Example //Student_Id and name bundled in a unit "Student" => encapsulation Let’s now implement the example of encapsulation in Java. To access these private member variables and change their values, we have to provide the public getter and setter methods respectively.Use the access modifier ‘private’ to declare the class member variables.In Java, there are two steps to implement encapsulation. In other words, it protects the sensitive data of our application. ![]() Thus encapsulation acts as a protective shield around the data and prevents the data from unauthorized access by the outside world. Similarly, data and methods are enclosed in a single unit in encapsulation. As we all know the medicine is enclosed inside a medical capsule. We can visualize encapsulation as a medical capsule. The above figure represents a class which is an encapsulation unit that bundles the data and methods operating on this data into a single unit.Īs encapsulation mainly deals with data, it is alternatively called “Data encapsulation”. Thus encapsulation is also a kind of “data hiding” although later in the tutorial we will see that encapsulation is not the same as data hiding. So what we conclude from the above definition is that we have hidden the data member variables inside a class and have also specified the access modifiers so that they are not accessible to the other classes. The methods in turn are accessed using the object of that class. ![]() These data member variables can be accessed indirectly using methods of the class in which they are declared. Using encapsulation we can also hide the class data members (variables) from the other classes.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |