Java Encapsulation
What is Encapsulation in Java?
- Encapsulation in Java refers to integrating data (variables) and code (methods) into a single unit.
- In encapsulation, a class's variables are hidden from other classes and can only be accessed by the methods of the class in which they are found.
- Encapsulation in Java is an object-oriented procedure of combining the data members and data methods of the class inside the user-defined class.
- It is important to declare this class as private.
- provide public get and set methods to access and update the value of a private variable
Get and Set
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get
or set
, followed by the name of the variable, with the first letter in upper case:
Example
public class Person { private String name; // private = restricted access // Getter public String getName() { return name; } // Setter public void setName( String newName) { this.name = newName; } }
Instead, we use the getName()
and setName()
methods to access and update the variable:
Example
public class Main { public static void main(String[] args) { Person myObj = new Person(); myObj.setName("John"); // Set the value of the name variable to "John" System.out.println(myObj.getName()); } } // Outputs "John"
Need for Encapsulation in Java:
- Encapsulation improvises the procedure of coding to a whole new level.
- Encapsulation provides ultimate control over the data members and data methods inside the class.
- Encapsulation prevents access to data members and data methods by any external classes. The encapsulation process improves the security of the encapsulated data.
- Changes made to one part of the code can be successfully implemented without affecting any other part of the code.