Encapsulation

What is Encapsulation?
  • Encapsulation is mechanism where we encapsulate the data (variables) and code acting on the data (methods) together as a single unit.
  • In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
  • To achieve encapsulation we need to declare the variables of a class as private and have to provide public setter and getter methods to modify and view the variables values.
Java Encapsulation
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class EncapsulationDemo {
 private String id;
 private String name;

 public String getId() {
  return id;
 }

 public String getName() {
  return name;
 }

 public void setId(String newId) {
  id = newId;
 }

 public void setName(String newName) {
  name = newName;
 }
}

<-- Previous || Next -->

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete