Encapsulation means, hiding sensitive data from users. Like capsule with hundreds of different medicines but none of the users aware of them.
To achieve this behavior in java, we must: => Declare our class members (attributes and methods) are private. => Use public get/set to access the private members.
Note: We know that private members can only be accessed within the declared class. But, outside the declared class, it is possible by using public getter and setter methods.
getter: returns the variable value
setter: set the variable value.
this keyword: indicates the current object.
Getter and setter syntax:
public data_type getV(type V){
return V;
}
public void setV(){
this.V = V;
}
V: name of the variable or method. It must start with capital letter.
Let's go through few examples:
Example 1:
Create 2 files in the src folder in your java project.
Person.java
TestExample.java
The Person class contains 2 private variables name and age. Including constructor (skip now), getter and setter methods. So that we can access the private members from outside the class.
The TestExample.java class contains the main method.
We now try to access the private fields (attributes) name and age of person class from the TestExample class. (skip the package details for the time being).
But we know that private members can only be accessed by get/set from outside the declared class.
So, after creating the object of the Person.java class, we use set method to set the value of the private message and get for getting the variable. (See in the below example)
//person.java
public class Person{
//private members
private String name;
private int age;
//constructor
//public getter and setter methods
//getter
public String getName(){
return name;
}
//setter
public void setName(String name){
this.name = name;
}
//getter
public int getAge(){
return age;
}
//setter
public void setAge(int age){
this.age = age;
}
}
// TestExample.java class
public class TestExample{
public static void main (String[] args) {
//create object of the Person class
Person person = new Person();
//set the value of the private members
person.setName("Mark Smith");
person.setAge(30);
//use getter for getting the values
System.out.println("Name is: "+person.getName());
System.out.println("Age is: "+person.getAge());
}
}
If you now run the TestExample.java class then you definitely get the following output in the console.
Name is: Mark Smith
Age is: 30
Why Encapsulation?
=> Better control of the class members like attributes and methods => Make the class attributes read only or write only. => For enhancing flexibility. Possible to change one part of the code without affecting other parts. => Increase security of the data. => For wrapping code or programs in a single unit.