Encapsulation in java:

Encapsulation is one of the four major concepts in oops.

By definition, encapsulation describes the idea of bundling data and methods that work on that data within one unit, like a class in Java. This concept is also often used to hide the internal representation, or state of an object from the outside. This is called information hiding.

Why do we need Encapsulation in Java?

The major advantage of encapsulation in Java is data hiding. Using encapsulation we can allow the programmer to decide on the access to data and methods operating on that data. For example, if we want a particular piece of data to be inaccessible to anyone outside the class, then we make that data private.

Uses of encapsulation:

  • Encapsulation makes programming flexible. This essentially means that you can edit and update code according to new specifications.
  • It helps you in achieving loose coupling.
  • Encapsulation makes the application simple and easy to debug.
  • You can change and make edits to your codebase without disrupting the normal functioning of your program.
  • Allows the programmer to control the data accessibility of a class.

Types of Encapsulation

Example program encapsulation:

  • Declare class variables as private or protected (if inheritance is used)
  • Assign setters and getters a public access specifier methods for modifying and viewing values of the variables

Example program:

public class EncapsulationEg {
 private String str;
 private String num;
 private int roll;

 public int getRoll() {
  return roll;
 }

 public String getCode() {
  return str;
 }

 public String getVal() {
  return num;
 }

 public void setRoll(int regn) {
  roll = regn;
 }

 public void setCode(String codeName) {
  str = codeName;
 }

 public void setVal(String id) {
  num = id;
 }
}

Disadvantages of Encapsulation

  • Code Size: The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers.
  • More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.

Leave a Comment