Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Encapsulation

Encapsulation

Encapsulation ensures that “sensitive” data is concealed from users. To accomplish this, you need to:

  • Declaring class variables/attributes as private.
  • Offering public get and set methods to access and modify the value of a private variable.

Get and Set

As learned from the previous chapter, private variables are only accessible within the same class, denying access from outside classes. Nonetheless, accessibility can be facilitated by providing public get and set methods.

The get method retrieves the variable value, while the set method assigns a value to it.

Both methods follow a syntax where they begin with either get or set, followed by the variable name, with the initial letter capitalized:

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;
  }
}

Example explained

The get method retrieves the value of the variable name.

The set method accepts a parameter (newName) and assigns it to the name variable. The “this” keyword is employed to reference the current object.

However, since the name variable is declared as private, access to it from outside this class is prohibited.

Example

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.name = "John";  // error
    System.out.println(myObj.name); // error 
  }
}

Had the variable been declared as public, the expected output would be as follows:

John

Attempting to access a private variable results in an error.

MyClass.java:4: error: name has private access in Person
    myObj.name = "John";
         ^
MyClass.java:5: error: name has private access in Person
    System.out.println(myObj.name);
                  ^
2 errors

Instead, we utilize the getName() and setName() methods to retrieve and modify 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"

Why Encapsulation?

  • Improved management of class attributes and methods.
  • Class attributes may be set to read-only (by exclusively utilizing the get method) or write-only (by solely employing the set method).
  • Flexible: Developers can modify one section of the code without impacting other sections.
  • Enhanced data security.