Java Encapsulation
Encapsulation
Encapsulation ensures that "sensitive" data is hidden from users. To achieve this, you must:
- Declare class variables/attributes as
private. - Provide
publicget and set methods to access and update the value of aprivatevariable.
Example: Get and Set Methods
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}Example: Accessing Private Variables
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());
}
}Output:
JohnWhy Encapsulation?
- Better control of class attributes and methods.
- Class attributes can be made read-only (if you only use the
getmethod) or write-only (if you only use thesetmethod). - Flexible: The programmer can change one part of the code without affecting other parts.
- Increased security of data.
Key Takeaways
- The dot (
.) is used to access the object's attributes and methods. - To call a method in Java, write the method name followed by parentheses
(), then a semicolon;. - A class must have a matching filename (e.g.,
MainandMain.java).