How to make an object completely encapsulated in java?


The process of wrapping up the data and, the code acting on the data together is known as encapsulation. This is a protective mechanism where we hide the data of one class from (an object of) another.

Since, variables hold the data of a class to encapsulate a class you need to declare the required variables (that you want to hide) private and provide public methods to access (read/write) them.

By doing so, you can access the variables only in the current class, they will be hidden from other classes, and can be accessed only through the provided methods. Therefore, it is also known as data hiding.

Encapsulating a class/object completely

To encapsulate a class/ object completely you need to

  • Declare all the variables of a the as private.
  • Provide public setter and getter methods to modify and view their values.

Example

In the following Java program, the Student class have two variables name and age. We are encapsulating this class by making them private and providing setter and getter methods.

If you want to access these variables you cannot access them directly, you can just use the provided setter and getter methods to read and write their values. The variables which you haven’t provided these methods will be completely hidden from the outside classes.

import java.util.Scanner;
class Student {
   private String name;
   private int age;
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void display() {
      System.out.println("name: "+getName());
      System.out.println("age: "+getAge());
   }
}
public class AccessData{
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      //Calling the setter and getter methods
      Student obj = new Student();
      obj.setName(name);
      obj.setAge(age);
      obj.display();
   }
}

Output

Enter the name of the student:
Krishna
Enter the age of the student:
20
name: Krishna
age: 20

Updated on: 02-Jul-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements