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

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 2013Juti Noppornpitak
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkitnikhilyagnic
 
Restful webservices for android
Restful webservices for android Restful webservices for android
Restful webservices for android Gowtham Kumar
 
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 SystemsTakuo Watanabe
 
Lecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadLecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadAtif Shahzad
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8Roland Mast
 
Using Affordance for Clearer Source Code
Using Affordance for Clearer Source CodeUsing Affordance for Clearer Source Code
Using Affordance for Clearer Source Codedavidolesch
 
Esoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessEsoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessChris Eargle
 
Programming Primer Encapsulation CS
Programming Primer Encapsulation CSProgramming Primer Encapsulation CS
Programming Primer Encapsulation CSsunmitraeducation
 
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 - UKOUGtogether21Oren Nakdimon
 

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 in Java explained with example

Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
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++ ExamsMuhammadTalha436
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Droolsgiurca
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
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 IEduardo Bergavera
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxShahinAhmed49
 
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)David McCarter
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 

Similar to Encapsulation in Java explained with example (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

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 NoidaDucat India
 
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 NoidaDucat India
 
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 noidaDucat India
 
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 NoidaDucat India
 
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 NoidaDucat India
 
Amazon Elastic Load Balancing
Amazon Elastic Load BalancingAmazon Elastic Load Balancing
Amazon Elastic Load BalancingDucat India
 
AWS Relation Database Services
AWS Relation Database ServicesAWS Relation Database Services
AWS Relation Database ServicesDucat India
 
Microsoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web ResourcesMicrosoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web ResourcesDucat India
 
Kanban Board in Jira
Kanban Board in JiraKanban Board in Jira
Kanban Board in JiraDucat India
 
Test Report Preparation
Test Report PreparationTest Report Preparation
Test Report PreparationDucat India
 
What is Text Analysis?
What is Text Analysis?What is Text Analysis?
What is Text Analysis?Ducat India
 
Data Science Using Scikit-Learn
Data Science Using Scikit-LearnData Science Using Scikit-Learn
Data Science Using Scikit-LearnDucat India
 
Struts 2 – Database Access
Struts 2 – Database AccessStruts 2 – Database Access
Struts 2 – Database AccessDucat India
 
Struts 2 – Interceptors
Struts 2 – InterceptorsStruts 2 – Interceptors
Struts 2 – InterceptorsDucat India
 
Struts 2 – Architecture
Struts 2 – ArchitectureStruts 2 – Architecture
Struts 2 – ArchitectureDucat India
 
Hibernate 5 – merge() Example
Hibernate 5 – merge() ExampleHibernate 5 – merge() Example
Hibernate 5 – merge() ExampleDucat India
 
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 DetachedDucat 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

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 

Recently uploaded (20)

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 

Encapsulation in Java explained with example

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