Encapsulation in Java with Examples

 

 

Introduction

Encapsulation is an OOP concept. It is a process of wrapping the data (variables) and code together into a single unit.

It is a concept of hiding data in a class, from other classes using data hiding. That’s why it is also known as data hiding.

 

What is Encapsulation?

It is wrapping code(method) and data (variables) together into one single unit.

 

A real-life example of Encapsulation, is A Capsule, in that capsule several medicines are mixed, and it is wrapped into one outer layer.

 

 

In the above diagram, you can see a class have data member and method (behavior) and both are combining. It makes that class an incapsulation class.

 

How to create a fully Encapsulation class in java?

By making all the data members of the class as private. we are making public setter and getter methods, in the class to set and get the data.

The Java Entity class (Bean class), is a fully encapsulated class in java.

 

Advantage of Encapsulation in Java.

There are many advantages of Encapsulation in java.

  • Make read-only and write-only classes using encapsulation.
  • Achieve data hiding.
  • The encapsulated classes are better for unit testing.
  • Easy and fast.
  • Control over data.

 

Java Simple Example of Encapsulation in Java

//A Java class which is a fully encapsulated class. 
package com.technicalround;

public class Employee {
// private data member
private Integer id;
private String name;
private String email;

// public getter method for name
public Integer getId() {
return id;
}

public String getName() {
return name;
}

public String getEmail() {
return email;
}

// public setter method for name
public void setName(String name){ 
this.name=name; 
}

public void setId(Integer id) {
this.id = id;
}


public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", email=" + email + "]";
}

}

 

Test.java

package com.technicalround;

class Test {
public static void main(String[] args) {
// creating instance of the encapsulated class
Employee emp = new Employee();

// setting value in member
emp.setId(1);
emp.setName("Niraj");
emp.setName("niraj@gmail.com");

// getting the value of a member
System.out.println(emp.getId);
System.out.println(emp.getName());
System.out.println(emp.getEmail());
}
}

Output:

1
Niraj
niraj@gmail.com

 

How to create a read-only class in java?

Make all data members(Variable) as private in java class. No setter methods, so not able to change data members, only the getter method for getting data, from another class, then this class automatically becomes a read-only class.

  • All data members(Variable) as private
  • No setter methods
  • Only the getter method for getting data

 

Read-Only class Java Programming Example.

package com.testing;

public class Employee {
// private data member
private String name;

// public getter method for name
public String getName() {
return name;
}
}

 

In the above example, we are not providing the setter method, so it can not be able to change from other classes.

 

How to create a write-only class in java?

Make all data members(Variable) as private in java class. No getter methods, so not able to get data members from others class, only the setter method for changing data, from another class, then this class automatically becomes a write-only class.

  • All data members(Variable) as private
  • No getter methods
  • Only the setting method for changing  data

 

Write-Only class Java Programming Example.

package com.testing;

public class Employee {
// private data member
private String name;

// public setter method for name
public void setName(String name) {
this.name = name;
}
}

 

In the above example, we are not providing the getter method, so it can not be able to read data from other classes.

 

Another Encapsulation Program.

//A Java class which is a fully encapsulated class. 
package com.technicalround;

public class User {
// private data member
private Integer id;
private String name;
private String email;
private String phoneNo;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", email=" + email + ", phoneNo=" + phoneNo + "]";
}

}

 

Java test class

package com.technicalround;

class Test {
public static void main(String[] args) {
// creating instance of the encapsulated class
User user = new User();

// setting value in member
user.setName(1);
user.setName("Niraj");
user.setName("niraj@gmail.com");
user.setPhoneNo("9988776655");

// getting the value of a member
System.out.println(user.getId);
System.out.println(user.getName());
System.out.println(user.getEmail());
System.out.println(user.getPhoneNo());
}
}

Output:

1
Niraj
niraj@gmail.com
9988776655

 

Different between Encapsulation and Abstraction.

Both Encapsulation and Abstraction are two of the four basic OOP concepts. In both are using for hiding data, but they hiding data in different ways. Sometimes we are confused between both of them.

  1.  Abstraction deals with “What” to hides. Encapsulation deals with “How” to hides.
  2.  Abstraction hides the complex functionalities. Encapsulation binds the functionalities.
  3.  Abstraction solves the problem at the design level. Encapsulation solves its implementation level.
  4.  Abstraction focus on the outer lookout. Encapsulation focuses on internal working(inner lookout).
  5.  Abstraction is about hiding unwanted details. Encapsulation means hiding the code and data into a single unit

 

Further other Topics:

 

Read more topics related to java

 

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

11 Replies to “Encapsulation in Java with Examples”

  1. I happen to be writing to make you understand what a wonderful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and helpful, trustworthy, revealing not to mention unique tips on your topic to Tanya.

  2. My spouse and i got quite joyful that Jordan managed to do his reports through the entire precious recommendations he had through the web pages. It is now and again perplexing to just continually be giving out procedures which people may have been selling. So we grasp we have got the writer to give thanks to for that. The most important illustrations you have made, the simple web site navigation, the relationships you will help foster – it’s got many incredible, and it’s really helping our son in addition to the family know that the situation is exciting, which is quite mandatory. Thank you for everything!

  3. I simply wished to thank you very much yet again. I do not know what I would have undertaken without those tips shown by you relating to this theme. Previously it was the terrifying setting in my view, nevertheless understanding your well-written technique you treated the issue took me to weep with joy. Now i’m thankful for your support as well as trust you recognize what an amazing job you were undertaking training the others via your website. Most probably you haven’t met any of us.

  4. I am commenting to let you know of the fantastic encounter my cousin’s daughter experienced reading your site. She even learned many issues, not to mention what it’s like to have a wonderful giving mindset to have many people quite simply grasp chosen grueling subject areas. You really exceeded our expectations. Many thanks for giving the informative, healthy, educational and as well as easy thoughts on the topic to Jane.

  5. I enjoy you because of all of your efforts on this site. Ellie enjoys doing internet research and it’s easy to see why. All of us hear all concerning the compelling manner you deliver functional ideas by means of the blog and as well cause contribution from other people about this concept plus my daughter is being taught a lot. Enjoy the remaining portion of the new year. You’re the one carrying out a first class job.

  6. My husband and i ended up being absolutely delighted that Jordan managed to do his reports through the entire precious recommendations he had through the web pages. It is now and again perplexing to just continually be giving out procedures which people may have been selling. So we grasp we have got the writer to give thanks to for that. The most important illustrations you have made, the simple web site navigation, the relationships you will help foster – it’s got many incredible, and it’s really helping our son in addition to the family know that the situation is exciting, which is quite mandatory. Thank you for everything!

  7. I’m commenting to let you be aware of of the beneficial discovery my child developed browsing the blog. She came to find a lot of details, including how it is like to have a great coaching character to get certain people completely comprehend a number of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel.

  8. I happen to be writing to make you understand what a wonderful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and helpful, trustworthy, revealing not to mention unique tips on your topic to Tanya.

Leave a Reply

Your email address will not be published.