Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is Encapsulation, Benefits, Implementation in Java

Similar presentations


Presentation on theme: "What is Encapsulation, Benefits, Implementation in Java"— Presentation transcript:

1 What is Encapsulation, Benefits, Implementation in Java
Java OOP Basics SoftUni Team Technical Trainers Software University

2 Table of Contents What is Encapsulation? Keyword this Access Modifiers
Validation Mutable and Immutable objects Keyword final

3 sli.do #Java-OOP Questions
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

4 Hiding Implementation
Encapsulation Hiding Implementation © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

5 Encapsulation Process of wrapping code and data together into a single unit Objects fields must be private Use getters and setters for data access class Person { private int age; } 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 class Person { public int getAge() public void setAge() } © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

6 Encapsulation – Example
Fields should be private Person -name : string -age : int +Person(string name, int age) +getName : String +getAge : int -setName(String name) : void -setAge(int age) : void Fields are private Constructors and accessors are defined (getters and setters) © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

7 Keyword this this is reference to the current object
this can refer current class instance variable this can invoke current class method public Person(String name) { this.name = name; } 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 private String getFirstName() { return this.fname } public String fullName() { return this.getFirstName() + " " + this.getLastName() } © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

8 Keyword this (2) this can invoke current class constructor
this can be pass like argument in method or constructor call this can be returned from method public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Person (String fname, String lName, Integer age) { this(fName, lName); this.age = age; 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 © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

9 Visibility of Class Members
Access Modifiers Visibility of Class Members © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

10 Private Access Modifier
Main way that an object encapsulates itself and hides data from the outside world Class and interfaces cannot be private Can only be accessed within the declared class itself class Person { private String name; Person (String name) { this.name = name; } 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. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

11 Protected Access Modifier
Can be accessed only by the subclasses in other package Protected access modifier cannot be applied to class and interfaces Preventing a nonrelated class from trying to use it class Team { protected String getName () protected void setName (String name) } 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. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

12 Default Access Modifier
Do not explicitly declare an access modifier Available to any other class in the same package class Team { String getName () void setName (String name) } 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. Team rm = new Team("Real"); rm.setName("Real Madrid"); System.out.println(rm.getName()); //Real Madrid © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

13 Public Access Modifier
A Class, method, constructor declared inside a public class can be accessed from any class belonging to the Java Universe Imports are needed if we try to access public class in different package The main() method of an application has to be public public class Team { public String getName () public void setName (String name) } 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. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

14 Problem: Sort Persons by Name and Age
Create a class Person Person -firstName:String -lastName:String -age:Integer +getFirstName():String +getAge():Integer +toString():String

15 Solution: Getters and Setters
public class Person { private String firstName; private String lastName; private Integer age; public String getFirstName() { return this.firstName; } public Integer getAge() { return age; } @Override public String toString() { TODO: Add logic} } Check your solution here:

16 Problem: Salary Increase
Expand Person with salary Add getter for salary Add method, which update salary with given percent Persons younger than 30 get half increase than normal Person -firstName : String -lastName : String -age : Integer -salary : Double +getFirstName() : String +getAge() : Integer +getSalary : Double +increaseSalary(Integer):void +toString() : String

17 Solution: Getters and Setters
Expand Person from previous task public class Person { private Double salary; public String getSalary() { return this.salary; } public void increaseSalary(Integer percentBonus) { if (this.age > 30) { this.salary += this.salary * bonus / 100; } else { this.salary += this.salary * bonus / 200; } } } Check your solution here:

18 Implement Getters and Setters
Exercises in Class Implement Getters and Setters

19 Encapsulation in Java © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

20 Better throw exception, than print to Console
Validation Data validation happen in setters Don’t couple your class with Console Contributor of your class have to think about handle Exceptions private void setSalary(Double salary) { if (salary < 460) { throw new IllegalArgumentException ("Salary cannot be less than 460 leva"); } this.salary = salary; Better throw exception, than print to Console 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 © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

21 Validation is happen inside of setter
Constructors use private setter with validation logic Guarantee valid state of object in its creation Guarantee valid state for public setters public Person(String firstName, String lastName, Integer age, Double salary) { setFirstName(firstName); setLastName(lastName); setAge(age); setSalary(salary); } Validation is happen inside of setter 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 © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

22 Problem: Validate Data
Expand Person with validation for every field Names must be at least 3 symbols Age cannot be zero or negative Salary cannot be less than 460 Person -firstName : String -lastName : String -age : Integer -salary : Double +Person() -setFirstName(String fname) -setLastName(String lname) -setAge(Integer age) -setSalary(Double salary)

23 Solution: Validate Data
TODO: Add validation for firstName TODO: Add validation for lastName private void setAge(Integer 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:

24 Immutable Objects When you have a reference to an instance of an object, the contents of that instance cannot be altered String myString = new String( "old String" ); System.out.println( myString ); myString.replaceAll( "old", "new" ); Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data old String © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

25 Mutable Objects When you have a reference to an instance of an object, the contents of that instance can be altered Point myPoint = new Point( 0, 0 ); System.out.println( myPoint ); myPoint.setLocation( 1.0, 0.0 ); Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data java.awt.Point[0.0, 0.0] java.awt.Point[1.0, 0.0] © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

26 Mutable Fields private mutable fields are still don’t encapsulated
In this case getter is setter too class Team { private String name; private List<Person> players; public List<Person> getPlayers() { return this.players; } Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

27 Mutable Fields (2) Return safe collections
For securing our collection we can return Collections.unmodifiableList() class Team { private List<Person> players; public addPlayer(Person person) { this.players.add(person); } public List<Person> getPlayers() { return Collections.unmodifiableList(players); Add new methods for functionality over list Fields are always declared private Accessed through getters and setters in read-only or read-write mode Setters perform checks to fight invalid data Return safe collections © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

28 Problem: First and Reserve Team
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 Team -name : String -firstTeam: List<Person> -reserveTeam: List<Person> +Team(String name) +getName() -setName(String name) +getFirstTeam(Integer age) +getReserveTeam(Double salary) +addPlayer(Person person)

29 Solution: Validate Data
private List<Person> firstTeam; private List<Person> reserveTeam; public addPlayer(Person person) { if (person.getAge() < 40) { firstTeam.add(person); } else { reserveTeam.add(person); } } public List<Person> getPlayers() { return Collections.unmodifiableList(firstTeam); } //TODO: add getter for reserve team Check your solution here:

30 Keyword final final class can't be extended
final method can't be overridden public class Animal {} public final class Mammal extends Animal {} public class Cat extends Mammal {} public class Animal { public final move(Point point) } public class Mammal extends Animal { @override public move() } 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 © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

31 Keyword final (2) Compile time error
final variable value can't be changed once it is set Private final String name; Private final List<Person> firstTeam; public Team (String name) { this.name = name; this.firstTeam = new ArrayList<Person> (); } public doSomething() { this.name = ""; this.firstTeam = new Arraylist<Person> (); this.firstTeam.add(Person person) Compile time error 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 © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

32 Encapsulation – Benefits
Reduces complexity Structural changes remain local Allows validations and data binding Ensures that structural changes remain local Changing the class internals does not break any outside code Allows changing the internal class implementation © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

33 Validations, Mutable and Immutable Objects
Exercises in Class Validations, Mutable and Immutable Objects

34 Summary Encapsulation hides implementation Access modifiers
Encapsulation reduces complexity Ensures that structural changes remain local Mutable objects Immutable objects

35 Java Syntax https://softuni.bg/courses/java-fundamentals
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

36 License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

37 Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.


Download ppt "What is Encapsulation, Benefits, Implementation in Java"

Similar presentations


Ads by Google