Java Encapsulation: Protecting Your Data
Learn about Java encapsulation, a fundamental principle of object-oriented programming that involves hiding sensitive data from users. Discover how to declare class variables as private and use public getter and setter methods to control access and modifications, ensuring data integrity and security in your Java applications.
Java Encapsulation
Encapsulation means hiding "sensitive" data from users. To achieve this:
- Declare class variables/attributes as private
- Provide public get and set methods to access and update the value of a private variable
Get and Set Methods
Private variables can only be accessed within the same class. To access them from outside, use public get and set methods:
Syntax
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Output
(Example of using get and set methods)
The get method returns the variable value, and the set method sets the value. The this
keyword refers to the current object.
Example of using get and set methods:
Syntax
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"
Output
John
Why Encapsulation?
- Better control of class attributes and methods
- Class attributes can be made read-only (using only get methods) or write-only (using only set methods)
- Flexible: change one part of the code without affecting other parts
- Increased security of data