Skip to content

Commit bb45114

Browse files
committed
encapsulation
1 parent a726c37 commit bb45114

File tree

1 file changed

+45
-12
lines changed

1 file changed

+45
-12
lines changed

encapsulation/readme.md

+45-12
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,64 @@
11
# Encapsulation
2+
23
Encapsulation is a process of wraping/combine/bind properties and methods (behavior) in a single unit or single container.
34

45
![https://www.sitesbay.com/cpp/images/encapsulation-in-cpp.png](https://www.sitesbay.com/cpp/images/encapsulation-in-cpp.png)
56

6-
all state is private , cannot change the state. Only can change with public function.
7+
All state are private , cannot change state. Only can change with public function.
78

8-
~ Encapsulation or information hiding
9+
# key points of encapsulation.
910

10-
~ Hide internal states and values inside a class, (safe the modification of state)
11+
* Information hiding
12+
* Hide internal states and behavior from external world
13+
* Protect the modification of state
1114

12-
```php
13-
class Cat
14-
{
15-
private hungry;
15+
# Example of encapsulation (php)
1616

17-
public function feedNow()
18-
{
19-
$this->hungry = 'feed';
17+
```php
18+
class BankAccount {
19+
private $balance;
20+
21+
public function __construct($initialBalance) {
22+
$this->balance = $initialBalance;
23+
}
24+
25+
public function deposit($amount) {
26+
$this->balance += $amount;
27+
}
28+
29+
public function withdraw($amount) {
30+
if ($this->balance >= $amount) {
31+
$this->balance -= $amount;
32+
} else {
33+
throw new Exception("Insufficient funds");
34+
}
35+
}
36+
37+
public function getBalance() {
38+
return $this->balance;
2039
}
2140
}
41+
42+
$bankAccount = new BankAccount(1000);
43+
44+
// Make a deposit
45+
$bankAccount->deposit(500);
46+
47+
// Make a withdrawal
48+
try {
49+
$bankAccount->withdraw(2000);
50+
} catch (Exception $e) {
51+
echo $e->getMessage(); // Output: Insufficient funds
52+
}
53+
54+
echo $bankAccount->getBalance(); // Output: 1500
2255
```
2356

24-
# encapsulation vs abstraction
57+
# Difference between encapsulation and abstraction
2558

2659
* https://stackoverflow.com/questions/15176356/difference-between-encapsulation-and-abstraction
2760

28-
# resources
61+
# Resources
2962

3063
* https://www.sitesbay.com/cpp/cpp-encapsulation
3164
* https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/

0 commit comments

Comments
 (0)