0% found this document useful (0 votes)
4 views29 pages

Chap1 Encapsulation

The document provides an overview of Object-Oriented Programming (OOP) with a focus on encapsulation, detailing its importance, core principles, and best practices. It explains how encapsulation protects data integrity and security while simplifying code maintenance and usability. Additionally, it includes exercises for practical application of concepts such as constructors and class design.

Uploaded by

phuthaidabong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Chap1 Encapsulation

The document provides an overview of Object-Oriented Programming (OOP) with a focus on encapsulation, detailing its importance, core principles, and best practices. It explains how encapsulation protects data integrity and security while simplifying code maintenance and usability. Additionally, it includes exercises for practical application of concepts such as constructors and class design.

Uploaded by

phuthaidabong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Programming

CO2039

Chapter 1: Object Oriented Programming


Revision - Encapsulation

ĐẠI HỌC QUỐC GIA THÀNH PHỐ HỒ CHÍ MINH


TRƯỜNG ĐẠI HỌC BÁCH KHOA
[Link], 03/01/2025
CONTENT
01 INTRODUCTION TO OOP

02 ENCAPSULATION

03 HOW ENCAPSULATION WORKS?

04 BEST PRACTICES

05 CONCLUSION

06 EXTENSION: CLASS DIAGRAM

2
INTRODUCTION TO
01 OBJECT ORIENTED
PROGRAMMING

3
What is OOP?
Object-oriented programming (OOP)
is a programming paradigm that
organizes software design around
objects, which can represent real-
world entities or abstract concepts.
Each object contains data (attributes
or properties) and behavior
(methods or functions).

4
Key principles of OOP
Encapsulation: Bundles data
(attributes) and methods (behavior)
into a single unit (class) and restricts
access to protect data integrity.

Example: A Car object has private


attribute speed and a public method
getSpeed() to access it.
=> Protects data integrity by
restricting direct access.
5
Key principles of OOP
Inheritance: Allows one class to
inherit attributes and methods from
another, promoting code reuse and
hierarchical relationships.

Example: A Truck class can inherit


from a Vehicle class.
=> Promotes code reuse.

6
Key principles of OOP
Polymorphism: Allows objects to
take on many forms, e.g., a single
method or class to represent
different underlying data types or
behaviors.

Example: A draw() method behaves


differently for Circle and Rectangle
objects.
=>Simplifies code and makes it
flexible. 7
Key principles of OOP
Abstraction: Hides implementation
details and exposes only essential
features, simplifying complex
systems for the user.

Example: A user presses a car's


"start" button without needing to
understand the engine mechanics.
=>Reduce complexity

8
Why OOP?
Create systems that are modular, scalable, reusable, and easier to
understand.
Think of a car in the real world. It has:
Attributes: color, brand, speed, fuel capacity.
Behaviors: start, stop, accelerate.
Modular -> divides programs into independent, self-contained classes
Scalable -> allows new functionality to be added or extended
Reusable -> creating generic classes or extending existing classes
Easier to understand -> models real-world entities with objects

9
02 ENCAPSULATION

10
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.

11
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.
12
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: Accessible only within the defining class.
default: Accessible only within the same package.
protected: Accessible within the same package and by subclasses (even
in different packages).
public: Accessible from anywhere (any class, any package, and any
subclass).
13
Example
public class Person {
// Public: Accessible anywhere
public String name;

// Protected: Accessible within the same package or by subclasses


protected int age;

// Default (Package-private): Accessible only within the same package


String address;

// Private: Accessible only within this class


private String password;

// Constructor to initialize the object


public Person(String name, int age, String address, String password) {
[Link] = name;
[Link] = age;
[Link] = address;
[Link] = password;
}

// Getter for password to demonstrate controlled access


public String getPassword() {
return password;
}
14
HOW
03 ENCAPSULATION
WORKS?

15
Class vs struct

Defining Classes and Objects


⇒ Can I use Struct instead of
Class?
Java: no struct
C++: class and struct
Struct Class

Default Access Public Private

Encapsulation Less support Full support

Use case Light weight objects All

16
Constructor in Encapsulation

A constructor is a special function in a class:


● Same name as the class.
● Not have a return value.
● It is automatically called when an object is created (the programmer
does not call it directly).
● If no constructor is declared, the program automatically provides a
default empty constructor.
⇒ What is the access modifier for the default constructor?
⇒ Can we create a private constructor? (Singleton Pattern)

17
Getters and Setters
• Example: Getters and Setters
public class Getset { are methods used to
private int age;
// Getter for 'age' access and modify
public int getAge() { the private fields of a
return age;
}
class, adhering to the
// Setter for 'age' with validation principles of
public void setAge(int age) { encapsulation
if (age >= 0) {
[Link] = age;
} else {
[Link]("Age cannot be negative.");
}
}
public static void main(String[] args) {
}
}
18
Getters and Setters
•Encapsulation: Protects the internal state of an object.
•Control: Allows you to validate or modify data before it's set.
•Consistency: Helps maintain consistent object state.
•Flexibility: Makes it easier to change the internal implementation
without affecting other code.
•Readability: Improves the readability and maintainability of the
code.
•Access Control: Allows creation of read-only or write-only
properties.
•Debugging: Enables easy tracking and debugging of changes to
the data.

19
04 BEST PRACTICES

20
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.
21
Exercise 2 - Constructor chaining

Create a Laptop class with attributes:


● brand (string)
● model (string)
● price (double)
Add the following:
● A default constructor.
● A parameterized constructor to initialize all attributes.
● Use constructor chaining to call one constructor from another.
Write a main function to test the class.

22
Exercise 3 (Bonus)

Create a Library system using encapsulation and constructors.


1. Create a Book class with attributes: title, author, ISBN, price, and stock.
2. Create a Library class with:
a. An array of Book objects.
b. Methods to:
i. Add new books.
ii. Search for books by title or author.
iii. Borrow books (reduce stock).
3. Write a main function to simulate library operations.

23
05 CONCLUSION

24
Conclusion

1. Encapsulation is the foundation of OOP, focusing on bundling data and


functions within a class.
2. The main difference between a class and a struct lies in the level of data
security (private/public).
3. A constructor is a special mechanism in OOP that automatically executes
when an object is created and can cause errors if not properly designed.

25
EXTENSION:
06 CLASS DIAGRAM

26
Class diagram

Can you write a program based on the above class diagram?

27
A class called Ball, which models
Hands-on exercise 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.
[Link]
line-compiler/5VrKcTuK0GRr6
28
Thank you for your attention!
[Link]

ĐẠI HỌC QUỐC GIA THÀNH PHỐ HỒ CHÍ MINH


TRƯỜNG ĐẠI HỌC BÁCH KHOA

You might also like