Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Implementing Encapsulation in Java

[post-views]

 

 

In this lesson, you will learn

  • Understanding Encapsulation in Java

 

Understanding Encapsulation in Java

  1. It is the technique of wrapping the data (variables) and code acting on the data (methods) together as a single unit.
  2. In encapsulation, the variables of a class are hidden from other classes and can be accessed only through the methods of their current class.
  3. Therefore, it is also known as data hiding.

 

To achieve encapsulation in Java:

  1. Declare the variables of a class as private.
  2. Provide public setter and getter methods to modify and view the variable values.

 

Example 1: Understanding Encapsulation

package ch9;

class Person {
    private String name; // Private variable, hidden from other classes
    private int age;     // Private variable, hidden from other classes

    // Getter method for name to read value
    public String getName() {
        return name;
    }

    // Setter method for name to modify value
    public void setName(String newName) {
        name = newName;
    }

    // Getter method for age to read value
    public int getAge() {
        return age;
    }

    // Setter method for age to modify value
    public void setAge(int newAge) {
        if(newAge > 0) { // Simple validation
            age = newAge;
        }
    }
}

public class PersonMain {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John"); // Setting the name using setter
        person.setAge(30);      // Setting the age using setter

        System.out.println("Name: " + person.getName() 
        	+", Age: " + person.getAge()); // Reading values using getters
    }
}

 

Output

Name: John, Age: 30

 

Explanation

  • The Person class has two private variables: name and age.
  • It has public setName and setAge methods to modify the values of name and age, respectively. This is an example of write properties.
  • It also has public getName and getAge methods to read the values of name and age, respectively. This is an example of read properties.

 

Through encapsulation, the actual representation of internal state is hidden from the outside, only allowing access through these public methods.

This way, you can ensure that Person objects are always in a consistent state and protect their internal data from unauthorized access.

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review