Chap1 Encapsulation v2
Chap1 Encapsulation v2
CO2039
03 BEST PRACTICES
04 CONCLUSION
2
INTRODUCTION TO
01 ENCAPSULATION
3
What is Encapsulation?
When creating new data types (classes) the details of the actual data
and the way operations work is hidden from the other programmers
who will use those new data types.
4
Why is Encapsulation important?
By controlling how data and methods are
accessed or modified, encapsulation ensures:
● Data Integrity: Prevents unauthorized or
accidental changes to data.
● Security: Sensitive data is hidden from
unauthorized access.
● Ease of Use: Users of the class do not need
to understand its internal complexities.
● Code Maintenance: Internal implementation
can change without impacting external
usage.
5
KEY CONCEPTS OF
02 ENCAPSULATION
6
How Encapsulation works?
7
Core principles of Encapsulation
Data Hiding: The internal state of an object is kept private and can only
be accessed through public methods (getters and setters).
Access Control: Access specifiers are used to control the visibility of class
members:
● private: members (attributes & methods) cannot be accessed (or
viewed) from outside the class ⇒ Default.
● protected: members cannot be accessed from outside the class, but
can be accessed in inherited classes. Learn more about Chap 2 -
Inheritance.
● public: members are accessible from outside the class.
8
How to write in Java & Python?
class BankAccount {
private:
double balance; string password;
public:
BankAccount(double initBalance, string pwd) :
balance(initBalance), password(pwd) {}
10
Setters & Getters
11
03 BEST PRACTICES
12
Exercise 1 - Multiple constructor
Create a Car class with the following private attributes:
● brand (string)
● model (string)
● year (int)
Add the following:
● A default constructor that sets default values.
● A parameterized constructor to initialize all attributes.
● Setters and getters for all attributes.
Write a main function to:
● Create an object using the default constructor and display its details.
● Create another object using the parameterized constructor and display its
details.
13
Exercise 2 - Constructor chaining
14
Exercise 3 (Bonus)
15
04 CONCLUSION
16
Conclusion
17
EXTENSION:
05 CLASS DIAGRAM
18
Class diagram
19
Hands-on exercise A class called Ball, which
models a bouncing ball, is
designed as shown in the
following class diagram.
It contains its radius, x and y
position. Each move-step
advances the x and y by delta-
x and delta-y, respectively.
delta-x and delta-y could be
positive or negative.
The reflectHorizontal() and
reflectVertical() methods
could be used to bounce the ball
off the walls. Write the Ball
class. Study the main() on how
the ball bounces.
https://www.programiz.com/onli
ne-compiler/5VrKcTuK0GRr6
20
Thank you for your
attention!
https://www.cse.hcmut.edu.vn