Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the bundling of fields and methods inside a single class, It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding.
Example 1: Java Encapsulation
Why Encapsulation?
Organization and Readability:
Encapsulation helps organize related fields and methods within a class, improving code readability.
Control over Data:
It provides control over data values, allowing for logic implementation, such as in setter methods.
Getter and Setter Methods:
Getter and setter methods offer controlled access to class fields.
Decoupling Components:
Encapsulation supports the development of decoupled components, enabling independent testing and debugging.
Data Hiding:
Data hiding is achieved by making fields private, restricting unauthorized access from outside the class.
Data Hiding Example:
In the above example, we have a private
field age. Since it is private
, it cannot be accessed from outside the class.
In order to access age, we have used public
methods: getAge()
and setAge()
. These methods are called getter and setter methods.
Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding.
If we try to access the age field from the Main class, we will get an error.
Last updated