What Is Encapsulation
What Is Encapsulation
Encapsulation is a way to restrict the direct access to some components of an object, so users
cannot access state values for all the variables of a particular object. Encapsulation can be used
to hide both data members and data functions or methods associated with an instantiated class
or object.
Hiding data: Users will have no idea how classes are being implemented or stored. All
that users will know is that values are being passed and initialized.
More flexibility: Enables you to set variables as red or write-only. Examples include:
setName(), setAge() or to set variables as write-only then you only need to omit the get
methods like getName(), getAge() etc.
Easy to reuse: With encapsulation, it's easy to change and adapt to new requirements
With a getter/setter method. A getter method is used to retrieve the value of a specific variable
within a class. A setter method is used to set or update the value of a specific variable within a
class. Programmers can use access modifiers to define the visibility and accessibility of classes,
along with the data and methods that they contain. In the Java programming language, there
are four types of access modifiers to choose from:
Private - When applied to an attribute or method, it can only be accessed by code within
the same class. As a result, the class will likely need to include getter and setter methods
that can be used to access the information.
Protected - A variable or method that is protected can be accessed by code within the
same class, by any classes that are in the same package and by all sub-classes in the
same or other packages.
Public - The public access modifier is the least restrictive of all. Methods, attributes, and
classes that are coded with this access modifier can be viewed and accessed by code
within the same class and within all other classes.
No modifier - When a variable has no access modifier, it can be accessed or viewed from
within the same class or from all other classes in the same package
In this example, the class “Person” encapsulates the name and age attributes.
By providing getter and setter methods we can access and modify them. The
private keyword ensures that these attributes are not directly accessible
from outside the class.