SlideShare a Scribd company logo
Benefits of Encapsulation
Encapsulation
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1. What is Encapsulation?
 Keyword this
2. Access Modifiers
3. Validation
4. Mutable and Immutable Objects
5. Keyword final
Table of Contents
2
sli.do
#java-advanced
Have a Question?
Hiding Implementation
Encapsulation
Abstraction
Information Hiding
Data Encapsulation
 Process of wrapping code and data together
into a single unit
 Flexibility and extensibility of the code
 Reduces complexity
 Structural changes remain local
 Allows validation and data binding
Encapsulation
5
 Objects fields must be private
 Use getters and setters for data access
Encapsulation
6
class Person {
private int age;
}
class Person {
public int getAge()
public void setAge(int age)
}
Encapsulation – Example
 Fields should be private
 Accessors and Mutators should be public
7
Person
-name: string
-age: int
+Person(String name, int age)
+getName(): String
+setName(String name): void
+getAge(): int
+setAge(int age): void
- == private
+ == public
 this is a reference to the current object
 this can refer to current class instance
 this can invoke current class method
Keyword this (1)
8
public Person(String name) {
this.name = name;
}
public String fullName() {
return this.getFirstName() + " " + this.getLastName();
}
 this can invoke current class constructor
Keyword this (2)
9
public Person(String name) {
this.firstName = name;
}
public Person (String name, Integer age) {
this(name);
this.age = age;
}
Access Modifiers
Visibility of Class Members
 Object hides data from the outside world
 Classes and interfaces cannot be private
 Data can be accessed only within the
declared class itself
Private Access Modifier
11
class Person {
private String name;
Person (String name) {
this.name = name;
}
}
 Grants access to subclasses
 protected modifier cannot be applied to
classes and interfaces
 Prevents a nonrelated class from trying to use it
Protected Access Modifier
12
class Team {
protected String getName () {…}
protected void setName (String name) {…}
}
 Do not explicitly declare an access modifier
 Available to any other class in the same package
Default Access Modifier
13
class Team {
String getName() {…}
void setName(String name) {…}
}
Team real = new Team("Real");
real.setName("Real Madrid");
System.out.println(real.getName());
// Real Madrid
 Grants access to any class belonging to
the Java Universe
 Import a package if you need to use a class
 The main() method of an application
must be public
Public Access Modifier
14
public class Team {
public String getName() {…}
public void setName(String name) {…}
}
 Create a class Person
Problem: Sort by Name and Age
15
Person
-firstName: String
-lastName: String
-age: int
+getFirstName(): String
+getLastName(): String
+getAge(): int
+toString(): String
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Solution: Sort by Name and Age
16
public class Person {
private String firstName;
private String lastName; private int age;
// TODO: Implement Constructor
public String getFirstName() { /* TODO */ }
public String getLastName() { /* TODO */ }
public int getAge() { return age; }
@Override
public String toString() { /* TODO */ }
}
 Implement Salary
 Add:
 getter for salary
 increaseSalary by percentage
 Persons younger than 30 get
only half of the increase
Problem: Salary Increase
17
Person
-firstName: String
-lastName: String
-age: int
-salary: double
+getFirstName(): String
+getLastName() : String
+getAge() : int
+getSalary(): double
+setSalary(double): void
+increaseSalary(double): void
+toString(): String
 Expand Person from previous task
Solution: Salary Increase (1)
18
public class Person {
private double salary;
// Edit Constructor
public double getSalary() {
return this.salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
// Next Slide…
// TODO: Edit toString() method
}
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
 Expand Person from previous task
Solution: Salary Increase (2)
19
public void increaseSalary(double percentage) {
if (this.getAge() < 30) {
this.setSalary(this.getSalary() +
(this.getSalary() * percentage / 200));
} else {
this.setSalary(this.getSalary() +
(this.getSalary() * percentage / 100));
}
}
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Validation
 Data validation happens in setters
 Printing with System.out couples your class
 Client can handle class exceptions
Validation (1)
21
private void setSalary(double salary) {
if (salary < 460) {
throw new IllegalArgumentException("Message");
}
this.salary = salary;
}
It is better to throw exceptions,
rather than printing to the Console
 Constructors use private setters with validation logic
 Guarantees valid state of object in its creation
 Guarantees valid state for public setters
Validation (2)
22
public Person(String firstName, String lastName,
int age, double salary) {
setFirstName(firstName);
setLastName(lastName);
setAge(age);
setSalary(salary);
}
Validation happens
inside the setter
 Expand Person with
validation for every field
 Names should be
at least 3 symbols
 Age cannot be zero or negative
 Salary cannot be less than 460
Problem: Validation Data
23
Person
-firstName : String
-lastName : String
-age : int
-salary : double
+Person()
+setFirstName(String fName)
+setLastName(String lName)
+setAge(int age)
+setSalary(double salary)
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Solution: Validation Data
24
// TODO: Add validation for firstName
// TODO: Add validation for lastName
public void setAge(int age) {
if (age < 1) {
throw new IllegalArgumentException(
"Age cannot be zero or negative integer");
}
this.age = age;
}
// TODO: Add validation for salary
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Mutable and Immutable Objects
25
Mutable vs Immutable Objects
 Mutable Objects
 The contents of that
instance can be altered
 Immutable Objects
 The contents of the
instance can't be altered
26
old String
old String
Point myPoint = new Point(0, 0);
myPoint.setLocation(1.0, 0.0);
System.out.println(myPoint);
java.awt.Point[1.0, 0.0]
String str = new String("old String");
System.out.println(str);
str.replaceAll("old", "new");
System.out.println(str);
 private mutable fields are not fully encapsulated
 In this case getter is like setter too
Mutable Fields
27
class Team {
private String name;
private List<Person> players;
public List<Person> getPlayers() {
return this.players;
}
}
Mutable Fields - Example
28
Team team = new Team();
Person person = new Person("David", "Adams", 22);
team.getPlayers().add(person);
System.out.println(team.getPlayers().size()); // 1
team.getPlayers().clear();
System.out.println(team.getPlayers().size()); // 0
 For securing our collection we can return
Collections.unmodifiableList()
Imutable Fields
29
class Team {
private List<Person> players;
public void addPlayer(Person person) {
this.players.add(person);
}
public List<Person> getPlayers() {
return Collections.unmodifiableList(players);
}
}
Returns a safe collections
Add new methods for
functionality over list
 Expand your project with class Team
 Team have two squads
first team and reserve team
 Read persons from console and
add them to team
 If they are younger than 40,
they go to first squad
 Print both squad sizes
Problem: First and Reserve Team
30
Team
-name: String
-firstTeam: List<Person>
-reserveTeam: List<Person>
+Team(String name)
+getName()
-setName(String name)
+getFirstTeam()
+getReserveTeam()
+addPlayer(Person person)
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Solution: First and Reserve Team
31
private List<Person> firstTeam;
private List<Person> reserveTeam;
public void addPlayer(Person person) {
if (person.getAge() < 40)
this.firstTeam.add(person);
else
this.reserveTeam.add(person);
}
public List<Person> getFirstTeam() {
return Collections.unmodifiableList(firstTeam);
}
// TODO: add getter for reserve team
Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
Keyword final
32
final
 final class can't be extended
 final method can't be overridden
Keyword final
33
public class Animal {}
public final class Mammal extends Animal {}
public class Cat extends Mammal {}
public final void move(Point point) {}
public class Mammal extends Animal {
@Override
public void move() {}
}
 final variable value can't be changed once it is set
Keyword final
34
private final String name;
private final List<Person> firstTeam;
public Team (String name) {
this.name = name;
this.firstTeam = new ArrayList<Person> ();
}
public void doSomething(Person person) {
this.name = "";
this.firstTeam = new ArrayList<>();
this.firstTeam.add(person);
}
Compile time error
 …
 …
 …
Summary
35
 Encapsulation:
 Hides implementation
 Reduces complexity
 Ensures that structural changes
remain local
 Mutable and Immutable objects
 Keyword final
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
License
40

More Related Content

What's hot

Files in java
Files in javaFiles in java
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
RAGAVIC2
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Wrapper classes
Wrapper classes Wrapper classes
Java package
Java packageJava package
Java package
CS_GDRCST
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
deepalishinkar1
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 

What's hot (20)

Files in java
Files in javaFiles in java
Files in java
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Java package
Java packageJava package
Java package
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 

Similar to 20.3 Java encapsulation

Assignment 7
Assignment 7Assignment 7
Assignment 7
IIUM
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
MohammedNouh7
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
Mahmoud Samir Fayed
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
11slide
11slide11slide
11slide
IIUM
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
Naresha K
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
Usama Malik
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
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
MuhammadTalha436
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Simple class and object examples in java
Simple class and object examples in javaSimple class and object examples in java
Simple class and object examples in java
Harish Gyanani
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
irshadkumar3
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 

Similar to 20.3 Java encapsulation (20)

Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
11slide
11slide11slide
11slide
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
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
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Simple class and object examples in java
Simple class and object examples in javaSimple class and object examples in java
Simple class and object examples in java
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
 
Core java oop
Core java oopCore java oop
Core java oop
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Refactoring
RefactoringRefactoring
Refactoring
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 

Recently uploaded

How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
VivekSinghShekhawat2
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 

Recently uploaded (20)

How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 

20.3 Java encapsulation

  • 1. Benefits of Encapsulation Encapsulation Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. 1. What is Encapsulation?  Keyword this 2. Access Modifiers 3. Validation 4. Mutable and Immutable Objects 5. Keyword final Table of Contents 2
  • 5.  Process of wrapping code and data together into a single unit  Flexibility and extensibility of the code  Reduces complexity  Structural changes remain local  Allows validation and data binding Encapsulation 5
  • 6.  Objects fields must be private  Use getters and setters for data access Encapsulation 6 class Person { private int age; } class Person { public int getAge() public void setAge(int age) }
  • 7. Encapsulation – Example  Fields should be private  Accessors and Mutators should be public 7 Person -name: string -age: int +Person(String name, int age) +getName(): String +setName(String name): void +getAge(): int +setAge(int age): void - == private + == public
  • 8.  this is a reference to the current object  this can refer to current class instance  this can invoke current class method Keyword this (1) 8 public Person(String name) { this.name = name; } public String fullName() { return this.getFirstName() + " " + this.getLastName(); }
  • 9.  this can invoke current class constructor Keyword this (2) 9 public Person(String name) { this.firstName = name; } public Person (String name, Integer age) { this(name); this.age = age; }
  • 11.  Object hides data from the outside world  Classes and interfaces cannot be private  Data can be accessed only within the declared class itself Private Access Modifier 11 class Person { private String name; Person (String name) { this.name = name; } }
  • 12.  Grants access to subclasses  protected modifier cannot be applied to classes and interfaces  Prevents a nonrelated class from trying to use it Protected Access Modifier 12 class Team { protected String getName () {…} protected void setName (String name) {…} }
  • 13.  Do not explicitly declare an access modifier  Available to any other class in the same package Default Access Modifier 13 class Team { String getName() {…} void setName(String name) {…} } Team real = new Team("Real"); real.setName("Real Madrid"); System.out.println(real.getName()); // Real Madrid
  • 14.  Grants access to any class belonging to the Java Universe  Import a package if you need to use a class  The main() method of an application must be public Public Access Modifier 14 public class Team { public String getName() {…} public void setName(String name) {…} }
  • 15.  Create a class Person Problem: Sort by Name and Age 15 Person -firstName: String -lastName: String -age: int +getFirstName(): String +getLastName(): String +getAge(): int +toString(): String Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 16. Solution: Sort by Name and Age 16 public class Person { private String firstName; private String lastName; private int age; // TODO: Implement Constructor public String getFirstName() { /* TODO */ } public String getLastName() { /* TODO */ } public int getAge() { return age; } @Override public String toString() { /* TODO */ } }
  • 17.  Implement Salary  Add:  getter for salary  increaseSalary by percentage  Persons younger than 30 get only half of the increase Problem: Salary Increase 17 Person -firstName: String -lastName: String -age: int -salary: double +getFirstName(): String +getLastName() : String +getAge() : int +getSalary(): double +setSalary(double): void +increaseSalary(double): void +toString(): String
  • 18.  Expand Person from previous task Solution: Salary Increase (1) 18 public class Person { private double salary; // Edit Constructor public double getSalary() { return this.salary; } public void setSalary(double salary) { this.salary = salary; } // Next Slide… // TODO: Edit toString() method } Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 19.  Expand Person from previous task Solution: Salary Increase (2) 19 public void increaseSalary(double percentage) { if (this.getAge() < 30) { this.setSalary(this.getSalary() + (this.getSalary() * percentage / 200)); } else { this.setSalary(this.getSalary() + (this.getSalary() * percentage / 100)); } } Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 21.  Data validation happens in setters  Printing with System.out couples your class  Client can handle class exceptions Validation (1) 21 private void setSalary(double salary) { if (salary < 460) { throw new IllegalArgumentException("Message"); } this.salary = salary; } It is better to throw exceptions, rather than printing to the Console
  • 22.  Constructors use private setters with validation logic  Guarantees valid state of object in its creation  Guarantees valid state for public setters Validation (2) 22 public Person(String firstName, String lastName, int age, double salary) { setFirstName(firstName); setLastName(lastName); setAge(age); setSalary(salary); } Validation happens inside the setter
  • 23.  Expand Person with validation for every field  Names should be at least 3 symbols  Age cannot be zero or negative  Salary cannot be less than 460 Problem: Validation Data 23 Person -firstName : String -lastName : String -age : int -salary : double +Person() +setFirstName(String fName) +setLastName(String lName) +setAge(int age) +setSalary(double salary) Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 24. Solution: Validation Data 24 // TODO: Add validation for firstName // TODO: Add validation for lastName public void setAge(int age) { if (age < 1) { throw new IllegalArgumentException( "Age cannot be zero or negative integer"); } this.age = age; } // TODO: Add validation for salary Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 25. Mutable and Immutable Objects 25
  • 26. Mutable vs Immutable Objects  Mutable Objects  The contents of that instance can be altered  Immutable Objects  The contents of the instance can't be altered 26 old String old String Point myPoint = new Point(0, 0); myPoint.setLocation(1.0, 0.0); System.out.println(myPoint); java.awt.Point[1.0, 0.0] String str = new String("old String"); System.out.println(str); str.replaceAll("old", "new"); System.out.println(str);
  • 27.  private mutable fields are not fully encapsulated  In this case getter is like setter too Mutable Fields 27 class Team { private String name; private List<Person> players; public List<Person> getPlayers() { return this.players; } }
  • 28. Mutable Fields - Example 28 Team team = new Team(); Person person = new Person("David", "Adams", 22); team.getPlayers().add(person); System.out.println(team.getPlayers().size()); // 1 team.getPlayers().clear(); System.out.println(team.getPlayers().size()); // 0
  • 29.  For securing our collection we can return Collections.unmodifiableList() Imutable Fields 29 class Team { private List<Person> players; public void addPlayer(Person person) { this.players.add(person); } public List<Person> getPlayers() { return Collections.unmodifiableList(players); } } Returns a safe collections Add new methods for functionality over list
  • 30.  Expand your project with class Team  Team have two squads first team and reserve team  Read persons from console and add them to team  If they are younger than 40, they go to first squad  Print both squad sizes Problem: First and Reserve Team 30 Team -name: String -firstTeam: List<Person> -reserveTeam: List<Person> +Team(String name) +getName() -setName(String name) +getFirstTeam() +getReserveTeam() +addPlayer(Person person) Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 31. Solution: First and Reserve Team 31 private List<Person> firstTeam; private List<Person> reserveTeam; public void addPlayer(Person person) { if (person.getAge() < 40) this.firstTeam.add(person); else this.reserveTeam.add(person); } public List<Person> getFirstTeam() { return Collections.unmodifiableList(firstTeam); } // TODO: add getter for reserve team Check your solution here :https://judge.softuni.bg/Contests/1535/Encapsulation-Lab
  • 33.  final class can't be extended  final method can't be overridden Keyword final 33 public class Animal {} public final class Mammal extends Animal {} public class Cat extends Mammal {} public final void move(Point point) {} public class Mammal extends Animal { @Override public void move() {} }
  • 34.  final variable value can't be changed once it is set Keyword final 34 private final String name; private final List<Person> firstTeam; public Team (String name) { this.name = name; this.firstTeam = new ArrayList<Person> (); } public void doSomething(Person person) { this.name = ""; this.firstTeam = new ArrayList<>(); this.firstTeam.add(person); } Compile time error
  • 35.  …  …  … Summary 35  Encapsulation:  Hides implementation  Reduces complexity  Ensures that structural changes remain local  Mutable and Immutable objects  Keyword final
  • 39.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 40.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 40

Editor's Notes

  1. Encapsulation hides the implementation details Class announces only a few operations (methods) available for its clients – its public interface All data members (fields) of a class should be hidden Accessed via properties (read-only and read-write) No interface members should be hidden Encapsulation == hide (encapsulate) data behind constructors and properties
  2. Encapsulation hides the implementation details Class announces only a few operations (methods) available for its clients – its public interface All data members (fields) of a class should be hidden Accessed via properties (read-only and read-write) No interface members should be hidden Encapsulation == hide (encapsulate) data behind constructors and properties
  3. Fields are private Constructors and accessors are defined (getters and setters)
  4. Constructors are declared public Constructors perform checks to keep the object state valid Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected
  5. Constructors are declared public Constructors perform checks to keep the object state valid Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected
  6. Access Level "public" When we use the modifier public in front of some element, we are telling the compiler, that this element can be accessed from every class, no matter from the current project (assembly), from the current package. The access level public defines the miss of restrictions regarding the visibility. This access level is the least restricted access level in Java. Access Level "private" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same package. Access Level “protected" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same namespace. Access Level “default" This is the default access level, i.e. it is used when there is no access level modifier in front of the respective element of a class. Members can be accessed only from the same package.
  7. Access Level "public" When we use the modifier public in front of some element, we are telling the compiler, that this element can be accessed from every class, no matter from the current project (assembly), from the current package. The access level public defines the miss of restrictions regarding the visibility. This access level is the least restricted access level in Java. Access Level "private" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same package. Access Level “protected" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same namespace. Access Level “default" This is the default access level, i.e. it is used when there is no access level modifier in front of the respective element of a class. Members can be accessed only from the same package.
  8. Access Level "public" When we use the modifier public in front of some element, we are telling the compiler, that this element can be accessed from every class, no matter from the current project (assembly), from the current package. The access level public defines the miss of restrictions regarding the visibility. This access level is the least restricted access level in Java. Access Level "private" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same package. Access Level “protected" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same namespace. Access Level “default" This is the default access level, i.e. it is used when there is no access level modifier in front of the respective element of a class. Members can be accessed only from the same package.
  9. Access Level "public" When we use the modifier public in front of some element, we are telling the compiler, that this element can be accessed from every class, no matter from the current project (assembly), from the current package. The access level public defines the miss of restrictions regarding the visibility. This access level is the least restricted access level in Java. Access Level "private" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same package. Access Level “protected" The access level private is the one, which defines the most restrictive level of visibility of the class and its elements. The modifier private is used to indicate, that the element, to which is issued, cannot be accessed from any other class (except the class, in which it is defined), even if this class exists in the same namespace. Access Level “default" This is the default access level, i.e. it is used when there is no access level modifier in front of the respective element of a class. Members can be accessed only from the same package.
  10. Constructors are declared public Constructors perform checks to keep the object state valid Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected
  11. Constructors are declared public Constructors perform checks to keep the object state valid Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected
  12. Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data
  13. Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data
  14. Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data
  15. Constructors are declared public Constructors perform checks to keep the object state valid Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected