Encapsulation in TypeScript: Private Attributes and Methods
Lesson Overview
Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!
Encapsulation Explained
Encapsulation in OOP wraps up data and methods into a class. This organizational approach tidies the code and reinforces security. If you were to code a multiplayer game, for example, you could create a Player class, encapsulating data (health, armor, stamina) and methods (receiveDamage, shieldHit, restoreHealth).
Now, player is an instance of the Player class on which you can call methods. You may notice the private keyword in the Player class definition; we will discuss the private keyword in the next section.
Remark the Privacy
In TypeScript, private attributes and methods are designated using the private keyword. Note that the constructor itself cannot be private.
Private attributes and methods are inaccessible directly from an instance. This arrangement helps maintain integrity.
