Java
Java Classess
Java Encapsulation

Java Encapsulation

Encapsulation

Encapsulation ensures that "sensitive" data is hidden from users. To achieve this, you must:

  • Declare class variables/attributes as private.
  • Provide public get and set methods to access and update the value of a private variable.

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:

John

Why Encapsulation?

  • Better control of class attributes and methods.
  • Class attributes can be made read-only (if you only use the get method) or write-only (if you only use the set method).
  • 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., Main and Main.java).