![]() |
The TypeScript access modifiers are used to regulate how different class members will be seen such as properties or methods, they have great significance in support of the Object-Oriented Programming principle of Encapsulation and information hiding, TypeScript has three types of access modifiers that are public, private and protected. Types of Access Modifiers1) Public Access ModifierThe modifier is public and facilitates access to class members within and outside of the class by anyone in the program. It is a default access modifier in TypeScript class members, so you do not have to mention it explicitly unless accessibility is your concern. Example: In the Animal class, the name is declared public, making it available outside of the class, using dot notation, we may get the name of an Animal object (dog).
Output: Dog 2) Private Access ModifierThe private modifier stops class member from being accessed by others except for the class it is declared in, it’s good for keeping secret its implementation details and protecting an object’s inner state. Example: Person declares quantity as private, preventing direct access from the outside, the public getSSN method can change the quantity while verifying its value (accessing quantity).
Output: 123-45-6789 3) Protected Access ModifierThe protected keyword is used to declare a class member so that it can be accessed by the class containing it and any of its subclasses, it comes handy when you want members of a class accessed in descendant classes but not outside. Example: Age is protected in User, enabling access within User and its subclass Employee. Employee’s getRetirementAge method calculates retirement age using age (protected).
Output: 95 ConclusionVisibility and accessibility of class members can be controlled by typescript access modifiers, by appropriately using public, private, protected access modifiers, you will have better encapsulation, data hiding and inheritance. |
Reffered: https://www.geeksforgeeks.org
TypeScript |
Related |
---|
![]() |
![]() |
|
|
|
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |