SlideShare a Scribd company logo
1 of 7
Welcome to Ducat India
Language | Industrial Training | Digital Marketing | Web
Technology | Testing+ | Database | Networking | Mobile
Application | ERP | Graphic | Big Data | Cloud Computing
Apply Now
Call us:
70-70-90-50-90
www.ducatindia.com
Encapsulation is the process of wrapping up of data (properties) and behavior (methods) of an object into a
single unit, and the unit here is a Class (or interface). English meaning of Encapsulate is to enclose or be
enclosed in or as if in a capsule.
In Java, everything is enclosed within a class or interface, unlike languages such as C and C++, where we
can have global variables outside classes. Encapsulation enables data hiding, hiding irrelevant information
from the users of a class and exposing only the relevant details required by the user. We can expose our
operations hiding the details of what is needed to operate. We can protect the internal state of an object by
hiding its attributes from the outside world (by making it private), and then exposing them through setter and
getter methods. Now the modifications to the object internals are only controlled through these methods. To
relate this to the real world, consider the automatic transmission on an automobile.
Consider the example of a linked list’s get size method. We might be now using a variable named size that is
updated on every insert/delete operation. Later we might decide to traverse the list and find size every time
someone asks for size. But if some code were directly accessing the size variable, we would have to change
all those code for this change. However if we were accessing the size variable through a get size method,
other code can still call that method, and we can do our changes in that method.
Setters and Getters
A setter is a method used to change the value of an attribute and a getter is a method used to get the value
of an attribute. There is a standard naming convention for getters and setters, but Java compiler won’t
complain even otherwise.
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
Here getName and setName are the getter and setter for the variable ‘name’ respectively. Since this is a
standard naming convention, many IDEs like eclipse will generate it for you in this form.
Simple Example of Encapsulation
class EncapsulationCompany{
private int Id;
private String empName;
private int empSalary;
//Getter and Setter methods
public int getEmpId(){
return Id;
}
public String getEmpName(){
return empName;
}
public int getEmpSalary(){
return empSalary;
}
public void setEmpSalary(int newValue){
empSalary = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpId(int newValue){
Id = newValue;
}
}
class EncapsTest{
public static void main(String args[]){
EncapsulationCompany obj = new EncapsulationCompany();
obj.setEmpName("Ajay");
obj.setEmpSalary(24000);
obj.setEmpId(1223);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee ID: " + obj.getEmpId());
System.out.println("Employee Salary: " + obj.getEmpSalary());
}
}
Output
Employee Name: Ajay
Employee ID: 1223
Employee Salary: 24000
In the above example, all the three data members (or data fields) are private(see: Access Modifiers in Java) which
cannot be accessed directly. These fields can be accessed via public methods only. Fields empName, Id and
empSalary are made hidden data fields using the encapsulation technique of OOPs.
Advantages of Encapsulation
• The main advantage of Encapsulation is; it secures our data.
• It provides us to control over the data.
• It is a way to achieve data hiding in Java because other class will not access the data through the private data
members.
• The fields of a class can be made read-only or write-only.
• In encapsulation, class is easy to test.
Thank you!!
Call us:
70-70-90-50-90
www.ducatindia.com

More Related Content

What's hot

Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
nikhilyagnic
 
Esoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessEsoteric LINQ and Structural Madness
Esoteric LINQ and Structural Madness
Chris Eargle
 

What's hot (20)

Drools
DroolsDrools
Drools
 
Neo4 j
Neo4 jNeo4 j
Neo4 j
 
Understanding Doctrine at True North PHP 2013
Understanding Doctrine at True North PHP 2013Understanding Doctrine at True North PHP 2013
Understanding Doctrine at True North PHP 2013
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Functional es6
Functional es6Functional es6
Functional es6
 
Spring data
Spring dataSpring data
Spring data
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
 
Java 7
Java 7Java 7
Java 7
 
Lodash js
Lodash jsLodash js
Lodash js
 
Restful webservices for android
Restful webservices for android Restful webservices for android
Restful webservices for android
 
A Reflective Approach to Actor-Based Concurrent Context-Oriented Systems
A Reflective Approach to Actor-Based Concurrent Context-Oriented SystemsA Reflective Approach to Actor-Based Concurrent Context-Oriented Systems
A Reflective Approach to Actor-Based Concurrent Context-Oriented Systems
 
DSLs In Erlang
DSLs In ErlangDSLs In Erlang
DSLs In Erlang
 
Lecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadLecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzad
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
 
Using Affordance for Clearer Source Code
Using Affordance for Clearer Source CodeUsing Affordance for Clearer Source Code
Using Affordance for Clearer Source Code
 
Esoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessEsoteric LINQ and Structural Madness
Esoteric LINQ and Structural Madness
 
Programming Primer Encapsulation CS
Programming Primer Encapsulation CSProgramming Primer Encapsulation CS
Programming Primer Encapsulation CS
 
Oren nakdimon - Write Less With More - UKOUGtogether21
Oren nakdimon - Write Less With More - UKOUGtogether21Oren nakdimon - Write Less With More - UKOUGtogether21
Oren nakdimon - Write Less With More - UKOUGtogether21
 

Similar to Encapsulation

Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
giurca
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 

Similar to Encapsulation (20)

Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Clean code
Clean codeClean code
Clean code
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Sling Models Overview
Sling Models OverviewSling Models Overview
Sling Models Overview
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Refactoring
RefactoringRefactoring
Refactoring
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 

More from Ducat India

More from Ducat India (20)

Join MCSA Server 2016 And 2019 Course In Noida
Join MCSA Server 2016 And 2019 Course In NoidaJoin MCSA Server 2016 And 2019 Course In Noida
Join MCSA Server 2016 And 2019 Course In Noida
 
Apply now for dot net training classes in Noida
Apply now for dot net training classes in NoidaApply now for dot net training classes in Noida
Apply now for dot net training classes in Noida
 
Apply now for linux training classes in noida
Apply now for linux training classes in noidaApply now for linux training classes in noida
Apply now for linux training classes in noida
 
Apply Now for DevOps Training Classes in Noida
Apply Now for DevOps Training Classes in NoidaApply Now for DevOps Training Classes in Noida
Apply Now for DevOps Training Classes in Noida
 
Apply Now for AutoCAD Training Course in Noida
Apply Now for AutoCAD Training Course in NoidaApply Now for AutoCAD Training Course in Noida
Apply Now for AutoCAD Training Course in Noida
 
Amazon Elastic Load Balancing
Amazon Elastic Load BalancingAmazon Elastic Load Balancing
Amazon Elastic Load Balancing
 
AWS Relation Database Services
AWS Relation Database ServicesAWS Relation Database Services
AWS Relation Database Services
 
Microsoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web ResourcesMicrosoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web Resources
 
Field Types
Field TypesField Types
Field Types
 
Sprint in jira
Sprint in jiraSprint in jira
Sprint in jira
 
JIRA Versions
JIRA VersionsJIRA Versions
JIRA Versions
 
Kanban Board in Jira
Kanban Board in JiraKanban Board in Jira
Kanban Board in Jira
 
Test Report Preparation
Test Report PreparationTest Report Preparation
Test Report Preparation
 
What is Text Analysis?
What is Text Analysis?What is Text Analysis?
What is Text Analysis?
 
Data Science Using Scikit-Learn
Data Science Using Scikit-LearnData Science Using Scikit-Learn
Data Science Using Scikit-Learn
 
Struts 2 – Database Access
Struts 2 – Database AccessStruts 2 – Database Access
Struts 2 – Database Access
 
Struts 2 – Interceptors
Struts 2 – InterceptorsStruts 2 – Interceptors
Struts 2 – Interceptors
 
Struts 2 – Architecture
Struts 2 – ArchitectureStruts 2 – Architecture
Struts 2 – Architecture
 
Hibernate 5 – merge() Example
Hibernate 5 – merge() ExampleHibernate 5 – merge() Example
Hibernate 5 – merge() Example
 
Hibernate Object States – Transient,Persistent and Detached
Hibernate Object States – Transient,Persistent and DetachedHibernate Object States – Transient,Persistent and Detached
Hibernate Object States – Transient,Persistent and Detached
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 

Encapsulation

  • 1. Welcome to Ducat India Language | Industrial Training | Digital Marketing | Web Technology | Testing+ | Database | Networking | Mobile Application | ERP | Graphic | Big Data | Cloud Computing Apply Now Call us: 70-70-90-50-90 www.ducatindia.com
  • 2. Encapsulation is the process of wrapping up of data (properties) and behavior (methods) of an object into a single unit, and the unit here is a Class (or interface). English meaning of Encapsulate is to enclose or be enclosed in or as if in a capsule. In Java, everything is enclosed within a class or interface, unlike languages such as C and C++, where we can have global variables outside classes. Encapsulation enables data hiding, hiding irrelevant information from the users of a class and exposing only the relevant details required by the user. We can expose our operations hiding the details of what is needed to operate. We can protect the internal state of an object by hiding its attributes from the outside world (by making it private), and then exposing them through setter and getter methods. Now the modifications to the object internals are only controlled through these methods. To relate this to the real world, consider the automatic transmission on an automobile. Consider the example of a linked list’s get size method. We might be now using a variable named size that is updated on every insert/delete operation. Later we might decide to traverse the list and find size every time someone asks for size. But if some code were directly accessing the size variable, we would have to change all those code for this change. However if we were accessing the size variable through a get size method, other code can still call that method, and we can do our changes in that method.
  • 3. Setters and Getters A setter is a method used to change the value of an attribute and a getter is a method used to get the value of an attribute. There is a standard naming convention for getters and setters, but Java compiler won’t complain even otherwise. private String name; public String getName() { return name; } public void setName(String name) { this.name=name; } Here getName and setName are the getter and setter for the variable ‘name’ respectively. Since this is a standard naming convention, many IDEs like eclipse will generate it for you in this form.
  • 4. Simple Example of Encapsulation class EncapsulationCompany{ private int Id; private String empName; private int empSalary; //Getter and Setter methods public int getEmpId(){ return Id; } public String getEmpName(){ return empName; } public int getEmpSalary(){ return empSalary; } public void setEmpSalary(int newValue){ empSalary = newValue; }
  • 5. public void setEmpName(String newValue){ empName = newValue; } public void setEmpId(int newValue){ Id = newValue; } } class EncapsTest{ public static void main(String args[]){ EncapsulationCompany obj = new EncapsulationCompany(); obj.setEmpName("Ajay"); obj.setEmpSalary(24000); obj.setEmpId(1223); System.out.println("Employee Name: " + obj.getEmpName()); System.out.println("Employee ID: " + obj.getEmpId()); System.out.println("Employee Salary: " + obj.getEmpSalary()); } }
  • 6. Output Employee Name: Ajay Employee ID: 1223 Employee Salary: 24000 In the above example, all the three data members (or data fields) are private(see: Access Modifiers in Java) which cannot be accessed directly. These fields can be accessed via public methods only. Fields empName, Id and empSalary are made hidden data fields using the encapsulation technique of OOPs. Advantages of Encapsulation • The main advantage of Encapsulation is; it secures our data. • It provides us to control over the data. • It is a way to achieve data hiding in Java because other class will not access the data through the private data members. • The fields of a class can be made read-only or write-only. • In encapsulation, class is easy to test.