OOP Encapsulation Introduction#
What Is The Encapsulation In OOP?#
Encapsulationin Java is a mechanism to wrap up variables(data) and methods(code) together as a single unit. It is the process of hiding information details and protecting data and behavior of the object.- In Java, a
classis an example ofencapsulationin that it consists of data and methods that have been bundled into a single unit (wrapping) and restricted accesses from other classes by access modifiers (hiding information). - To achieve
encapsulationin Java, a class has to set attributes (variables) asprivateand provide publicsetterandgettermethods to modify and view these attributes. See example below.
Encapsulation Example#
- Create an
encapsulationclass with name Motorcycle.
| Motorcycle.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
- Test the class Motorcycle.
| Main.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 | |