In TypeScript, the main access modifiers for classes are public, private, and protected. These modifiers define the access level for class members (properties and methods).
- public (Public): This is the default access level. Members marked as
publiccan be accessed anywhere, both inside and outside the class. This means that any place where an instance of the class is created can access and modify these members.
Example:
typescriptclass Animal { public name: string; constructor(name: string) { this.name = name; } public display(): void { console.log(this.name); } } let dog = new Animal("Buddy"); dog.display(); // Output: Buddy console.log(dog.name); // Output: Buddy
- private (Private): Members marked as
privatecan only be accessed within the class. This means these members cannot be directly accessed outside the class or in any subclass that inherits from it.
Example:
typescriptclass Animal { private name: string; constructor(name: string) { this.name = name; } display(): void { console.log(this.name); } } let cat = new Animal("Whiskers"); cat.display(); // Output: Whiskers // console.log(cat.name); // Error: Property 'name' is private and only accessible within class 'Animal'.
- protected (Protected): Members marked as
protectedcan be accessed within the class and in any subclass that inherits from it. However, they cannot be directly accessed outside class instances.
Example:
typescriptclass Animal { protected name: string; constructor(name: string) { this.name = name; } } class Cat extends Animal { constructor(name: string) { super(name); } display(): void { console.log(this.name); } } let cat = new Cat("Paws"); cat.display(); // Output: Paws // console.log(cat.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
These access modifiers help implement encapsulation and hide internal implementation details, contributing to clean and secure code.
2024年8月2日 13:49 回复