OOP Encapsulation Introduction#
What Is The Encapsulation In OOP?#
Encapsulation
in 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
class
is an example ofencapsulation
in 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
encapsulation
in Java, a class has to set attributes (variables) asprivate
and provide publicsetter
andgetter
methods to modify and view these attributes. See example below.
Encapsulation Example#
- Create an
encapsulation
class 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 |
|