Hello! Today's journey ventures into the cornerstone of TypeScript's object-oriented fundamentals: Encapsulation. This concept establishes a protective barrier around an object's data, thereby preventing it from being accessed by the external code ecosystem. Let's dive in.
Encapsulation serves three main purposes: it maintains integrity, controls data modification, and provides data abstraction — interfaces that are accessible to users. Think of using a cell phone; you interact with an interface without interfering with its circuits. Following this logic, encapsulation safeguards the internal implementation while exposing safe interfaces.
Now, let's discuss Private Data: In TypeScript, we can specify private
data using the keyword private
. These data fields cannot be accessed outside the class. We will illustrate this with a Car
class, introducing a private
attribute called _speed
:
This class has a private member, _speed
, which cannot be accessed directly outside the class. The underscore _
before is a naming convention that indicates it is a private attribute.
