SlideShare a Scribd company logo
1 of 20
Lecture – 7
Encapsulation in Java
Lecturer
Department of CSE
Daffodil International University
Contents
• Encapsulation in Java
• How to implement encapsulation
• Advantage of Encapsulation
• Useful Links
2
Topic : Encapsulation in Java
3
Introduction to Encapsulation
• Encapsulation is one of the four fundamental OOP concepts.
• The other three are inheritance, polymorphism, and abstraction.
• It is the process of binding data and the corresponding methods under a single unit.
• It is the process of hiding information details and protecting data and behavior of the
object.
• 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.
4
To achieve this, you must:
1. declare class variables/attributes as private
2. provide public get and set methods to access and update the value of a
private variable
How to implement encapsulation
5
• We know, private variables can only be accessed within the same class (an outside
class has no access to it). However, it is possible to access them if we provide
public get and set methods.
• The get method returns the variable value, and the set method sets the value.
• Syntax for both is that they start with either get or set, followed by the name of
the variable, with the first letter in upper case:
e.g. If the name of the variable is studntID, then the methods names will be
getStudentId() and setStudentId().
Get and Set Methods
6
public class Person {
private String name; // private = restricted access
// Setter Method
public void setName (String newName) {
this.name = newName;
}
// Getter Method
public String getName() {
return name;
}
}
Example – 1
7
• The set method takes a parameter (newName) and assigns it to the name variable. The
‘this’ keyword is used to refer to the current object.
• The get method returns the value of the name variable.
• However, as the name variable is declared as private, we cannot access it from outside this
class
Example - 1 explained
8
As the name variable is declared as private, we cannot access it from outside this class
public class Person {
private String name; // private = restricted access
// Setter
public void setName (String newName) {
this.name = newName;
}
// Getter
public String getName() {
return name;
}
}
Example – 1 (Error)
9
public class Main
{
public static void main(String[] args)
{
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
We can access the private variables with setter and getter methods of that calss.
public class Person {
private String name; // private = restricted access
// Setter
public void setName (String newName) {
this.name = newName;
}
// Getter
public String getName() {
return name;
}
}
Example – 1
10
public class Main
{
public static void main(String[] args)
{
Person myObj = new Person();
myObj.setName("John");
// Set the value of the name variable
to “John"
System.out.println(myObj.getName());
}
}
// Outputs "John"
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName()
{
return name;
}
public int getAge() {
return age;
}
}
Example – 2
11
public class EncapsulaionExample
{
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("Asha");
p1.setAge(20);
System.out.println("Name: "+p1.getName());
System.out.println("Age: "+p1.getAge());
}
}
// Outputs
Name: Asha
Age: 20
UML representation of Example – 2
12
Person
- name: String
- age: int
+Person(String, int)
+setName(String) : void
+setId(int) : void
+getName(): String
+getId():int
MyClass
+main(String [] ) : void
13
Check Balance
Update Balance
ATM GUI
Data Hiding: By declaring variables as private, we can
achieve data hiding. we cannot access it from outside this
class
Abstraction: Highlighting the service that are offering
without explaining internal design/information is the
concept of Abstraction.
Using ATM Card,
⮚ We just swipe the card
⮚ Enter the password
⮚ Do the transaction
⮚ We don’t know the internal procedure. Being the end
user we just need to knowhow to use the card.
[Encapsulation = Data Hiding + Abstraction]
public class Account {
private double balance; // data hiding
public double getBalance () {
//Validation
return balance;
}
public void setBalance(double balance) {
//Validation
this.balance = balance;
}
}
Example – 2
[Encapsulation = Data Hiding + Abstraction]
14
Check Balance
Update Balance
ATM GUI
Example – 3.1
15
Student
- name: String
- id: int
- cgpa : double
+setName(String) : void
+setId(int) : void
+setCgpa(double): void
+getName():String
+getId(): int
+getCgpa () : double
MyClass
+main(String [] ) : void
Example – 3.2
16
Student
- name: String
- id: int
- cgpa : double
+Student(String, int, double)
+setName(String) : void
+setId(int) : void
+setCgpa(double): void
+getName():String
+getId(): int
+getCgpa () : double
MyClass
+main(String [] ) : void
Example – 4
17
Employee
- name: String
- id: int
- salary : double
+Employee(String, int, double)
+setName(String) : void
+setId(int) : void
+setSalary(double): void
+getName():String
+getId(): int
+getSalary() : double
MyClass
+main(String [] ) : void
• Data Hiding: It is a way to achieve data hiding in Java because other class will not be able
to access the data through the private data members. It increases the security of data
• Increased Flexibility: By providing only a setter or getter method, you can make the
class read-only or write-only depending on our requirement.
• Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements. The programmer can change one part of the code without affecting other
parts.
• Testing code is easy: Encapsulated code is easy to test for unit testing.
Advantage of Encapsulation
18
• https://www.tutorialspoint.com/java/java_encapsulation.htm
• https://beginnersbook.com/2013/05/encapsulation-in-java/
• https://www.javatpoint.com/encapsulation
• https://techvidvan.com/tutorials/java-encapsulation/
• Video Tutorial:
• https://www.youtube.com/watch?v=QFl9HhrpRFA
• https://www.youtube.com/watch?v=cU94So54cr8
19
Some helpful Links
Thank you!
20

More Related Content

What's hot

What's hot (20)

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Java package
Java packageJava package
Java package
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 

Similar to Lecture_7-Encapsulation in Java.pptx

Similar to Lecture_7-Encapsulation in Java.pptx (20)

C++Presentation 2.PPT
C++Presentation 2.PPTC++Presentation 2.PPT
C++Presentation 2.PPT
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
OOP presentation.pptx
OOP presentation.pptxOOP presentation.pptx
OOP presentation.pptx
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
OOP_presentation.pptx
OOP_presentation.pptxOOP_presentation.pptx
OOP_presentation.pptx
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
psnreddy php-oops
psnreddy  php-oopspsnreddy  php-oops
psnreddy php-oops
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
oopusingc.pptx
oopusingc.pptxoopusingc.pptx
oopusingc.pptx
 

More from ShahinAhmed49

BDBO Presentation.pptx
BDBO Presentation.pptxBDBO Presentation.pptx
BDBO Presentation.pptxShahinAhmed49
 
presentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxpresentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxShahinAhmed49
 
Presentation-10.pptx
Presentation-10.pptxPresentation-10.pptx
Presentation-10.pptxShahinAhmed49
 
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptx
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptxLecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptx
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptxShahinAhmed49
 
Lecture_4-Class and Object.pptx
Lecture_4-Class and Object.pptxLecture_4-Class and Object.pptx
Lecture_4-Class and Object.pptxShahinAhmed49
 
presentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxpresentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxShahinAhmed49
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxShahinAhmed49
 
Sentence Fragments(AA).pptx
Sentence Fragments(AA).pptxSentence Fragments(AA).pptx
Sentence Fragments(AA).pptxShahinAhmed49
 

More from ShahinAhmed49 (9)

BDBO Presentation.pptx
BDBO Presentation.pptxBDBO Presentation.pptx
BDBO Presentation.pptx
 
presentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxpresentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptx
 
Presentation-10.pptx
Presentation-10.pptxPresentation-10.pptx
Presentation-10.pptx
 
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptx
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptxLecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptx
Lecture_9-UML Basics_Inheritance_Association, Aggregation, Composition.pptx
 
Lecture_4-Class and Object.pptx
Lecture_4-Class and Object.pptxLecture_4-Class and Object.pptx
Lecture_4-Class and Object.pptx
 
presentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptxpresentationonanalogtransmission-210806163622.pptx
presentationonanalogtransmission-210806163622.pptx
 
Data (2).pptx
Data (2).pptxData (2).pptx
Data (2).pptx
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
Sentence Fragments(AA).pptx
Sentence Fragments(AA).pptxSentence Fragments(AA).pptx
Sentence Fragments(AA).pptx
 

Recently uploaded

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
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)

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.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
 

Lecture_7-Encapsulation in Java.pptx

  • 1. Lecture – 7 Encapsulation in Java Lecturer Department of CSE Daffodil International University
  • 2. Contents • Encapsulation in Java • How to implement encapsulation • Advantage of Encapsulation • Useful Links 2
  • 4. Introduction to Encapsulation • Encapsulation is one of the four fundamental OOP concepts. • The other three are inheritance, polymorphism, and abstraction. • It is the process of binding data and the corresponding methods under a single unit. • It is the process of hiding information details and protecting data and behavior of the object. • 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. 4
  • 5. To achieve this, you must: 1. declare class variables/attributes as private 2. provide public get and set methods to access and update the value of a private variable How to implement encapsulation 5
  • 6. • We know, private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods. • The get method returns the variable value, and the set method sets the value. • Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case: e.g. If the name of the variable is studntID, then the methods names will be getStudentId() and setStudentId(). Get and Set Methods 6
  • 7. public class Person { private String name; // private = restricted access // Setter Method public void setName (String newName) { this.name = newName; } // Getter Method public String getName() { return name; } } Example – 1 7
  • 8. • The set method takes a parameter (newName) and assigns it to the name variable. The ‘this’ keyword is used to refer to the current object. • The get method returns the value of the name variable. • However, as the name variable is declared as private, we cannot access it from outside this class Example - 1 explained 8
  • 9. As the name variable is declared as private, we cannot access it from outside this class public class Person { private String name; // private = restricted access // Setter public void setName (String newName) { this.name = newName; } // Getter public String getName() { return name; } } Example – 1 (Error) 9 public class Main { public static void main(String[] args) { Person myObj = new Person(); myObj.name = "John"; // error System.out.println(myObj.name); // error } }
  • 10. We can access the private variables with setter and getter methods of that calss. public class Person { private String name; // private = restricted access // Setter public void setName (String newName) { this.name = newName; } // Getter public String getName() { return name; } } Example – 1 10 public class Main { public static void main(String[] args) { Person myObj = new Person(); myObj.setName("John"); // Set the value of the name variable to “John" System.out.println(myObj.getName()); } } // Outputs "John"
  • 11. public class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } } Example – 2 11 public class EncapsulaionExample { public static void main(String[] args) { Person p1 = new Person(); p1.setName("Asha"); p1.setAge(20); System.out.println("Name: "+p1.getName()); System.out.println("Age: "+p1.getAge()); } } // Outputs Name: Asha Age: 20
  • 12. UML representation of Example – 2 12 Person - name: String - age: int +Person(String, int) +setName(String) : void +setId(int) : void +getName(): String +getId():int MyClass +main(String [] ) : void
  • 13. 13 Check Balance Update Balance ATM GUI Data Hiding: By declaring variables as private, we can achieve data hiding. we cannot access it from outside this class Abstraction: Highlighting the service that are offering without explaining internal design/information is the concept of Abstraction. Using ATM Card, ⮚ We just swipe the card ⮚ Enter the password ⮚ Do the transaction ⮚ We don’t know the internal procedure. Being the end user we just need to knowhow to use the card. [Encapsulation = Data Hiding + Abstraction]
  • 14. public class Account { private double balance; // data hiding public double getBalance () { //Validation return balance; } public void setBalance(double balance) { //Validation this.balance = balance; } } Example – 2 [Encapsulation = Data Hiding + Abstraction] 14 Check Balance Update Balance ATM GUI
  • 15. Example – 3.1 15 Student - name: String - id: int - cgpa : double +setName(String) : void +setId(int) : void +setCgpa(double): void +getName():String +getId(): int +getCgpa () : double MyClass +main(String [] ) : void
  • 16. Example – 3.2 16 Student - name: String - id: int - cgpa : double +Student(String, int, double) +setName(String) : void +setId(int) : void +setCgpa(double): void +getName():String +getId(): int +getCgpa () : double MyClass +main(String [] ) : void
  • 17. Example – 4 17 Employee - name: String - id: int - salary : double +Employee(String, int, double) +setName(String) : void +setId(int) : void +setSalary(double): void +getName():String +getId(): int +getSalary() : double MyClass +main(String [] ) : void
  • 18. • Data Hiding: It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. It increases the security of data • Increased Flexibility: By providing only a setter or getter method, you can make the class read-only or write-only depending on our requirement. • Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements. The programmer can change one part of the code without affecting other parts. • Testing code is easy: Encapsulated code is easy to test for unit testing. Advantage of Encapsulation 18
  • 19. • https://www.tutorialspoint.com/java/java_encapsulation.htm • https://beginnersbook.com/2013/05/encapsulation-in-java/ • https://www.javatpoint.com/encapsulation • https://techvidvan.com/tutorials/java-encapsulation/ • Video Tutorial: • https://www.youtube.com/watch?v=QFl9HhrpRFA • https://www.youtube.com/watch?v=cU94So54cr8 19 Some helpful Links