Encapsulation in Java || Getter and Setter Method in Java || Java OOPs Concepts Tutorials

Опубликовано: 06 Октябрь 2024
на канале: Learning and Teaching Coding
3,810
123

=== Video link ===
Access Modifiers In Java :    • Access Modifiers in Java || Private, ...  

The process of binding data and corresponding methods (behavior) together into a single unit is called encapsulation in Java.

=== What is encapsulation? ===
The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class.

No outside class can access private data member (variable) of other class.

-If we setup public getter and setter methods to update and read the private data fields then the outside class can access those private data fields via public methods.

This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes.

That’s why encapsulation is known as data hiding.

In the encapsulation technique, we declare fields as private in the class to prevent other classes from accessing them directly.

The required encapsulated data can be accessed by using public Java getter and setter method.

=== Getter method in Java ===
A method which is used to retrieve/get the value of a variable or return the value of the private member variable is called getter method in Java.

This method is also known as accessor method.

The signature of a getter method in Java :
public returnType getPropertyName()

=== Setter method in Java ===
A method which is used for updating or setting the value of a variable is called setter method in Java.

This method is also known as mutator method.

By using the setter method, we can modify the value of a variable.

Just like with the getter method, we should create a setter method for every variable in the class.

The signature of setter method in Java :
public void setPropertyName(dataType propertyValue)

=== Naming convention of Getter and Setter method ===
For example:
If the variable is the type of int, you will declare like this:

private int number;

then appropriate getter and setter will be like this:

public getNumber() { }
public void setNumber(int number) { }

=== Key points ===
1. If you define only the getter method, it can be made read-only.

2. If you define only the setter method, it can be made write-only.

3. If you define both getter and setter methods, it can be made read-write.

#JavaOOPsConceptsTutorials
#LearningandTeachingCoding