- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is encapsulation in Java?
Encapsulation in Java is a mechanism for wrapping 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 in Java:
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
Example
public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } public class RunEncap { public static void main(String args[]) { EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()); } }
Output
Name : James Age : 20
- Related Articles
- Encapsulation in Java
- What is encapsulation in C#?
- What is Encapsulation in Python?
- What is the difference between abstraction and encapsulation in Java?
- Abstraction vs Encapsulation in Java
- Advantages of encapsulation in Java
- What is Generic Routing Encapsulation (GRE)?
- How is encapsulation implemented in C#?
- Encapsulation in C++
- Encapsulation in C#
- How to implement the encapsulation concept in JShell in Java 9?
- Explain Encapsulation in PHP.
- How Does Encapsulation Work in Ruby?
- Golang Program to Show Encapsulation in Class
- JavaScript Encapsulation using Anonymous Functions

Advertisements