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

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
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
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
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
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
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
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
 
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
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
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
 

Recently uploaded (20)

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
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
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
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
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
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
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
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
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
 
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
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
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
 

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.