Java Programming Tutorial Index

Java Object Oriented

The concept of encapsulation is one of the four elementary concepts of Object Oriented Programming Language.



Encapsulation can be defined as the procedure of casing up of codes and their associated data jointly into one single component, like a medicine capsule having different components packed as a single unit. In Java, you can construct a completely encapsulated class by making all of its member data within a class as private (which is an access specifier). Moreover, you can implement the setter and the getters to set and get data from within a class.

In simple terms, encapsulation is a way of packaging data and methods together into one unit. Encapsulation gives us the ability to make variables of a class keep hidden from all other classes of that program or namespace. Hence, this concept provides programmers to achieve data hiding. To achieve encapsulation in Java:

  • 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:

// Here's an example how how encapsulation can be achieved
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;
 }
}

Here, first, you have defined a class name EncapsulationEg. Then assign three variables within the class by the name str and num, having a type as String and roll as integer type having private as access specifier to make the data hiding possible. Then you have to add set methods and get methods as public as access points of those instance variables. A name categorizes these methods as getters and setters.

Advantages of Encapsulation

  1. Class fields can be made read-only or write-only
  2. Programmers can have full control over what data storage and manipulation within the class


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram