Day 14: Encapsulation
Day 14:
Encapsulation:
Encapsulation in Java is integrating the data (fields) and the methods that operate on the data into a single unit and restricting the direct access to some of the object's components.
Encapsulation is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class.
In Java, encapsulation is achieved by declaring the instance variables of a class as private, which means they can only be accessed within the class. To allow outside access to the instance variables, public methods called getters and setters are defined, which are used to retrieve and modify the values of the instance variables, respectively. By using getters and setters, the class can enforce its own data validation rules and ensure that its internal state remains consistent.
It helps in two key things:
Data Hiding: The fields of a class are declared private to restrict direct access from outside the class.
Access Control: Public getter and setter methods are provided to access and modify the private fields in a controlled manner. Data Hiding: The fields of a class are declared private to restrict direct access from outside the class.
Example:
Happy Learning :)