class Person {
public name: string;
private age: number;
protected email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
introduce(): void {
console.log(`Hi, I'm ${this.name}, and I'm ${this.age} years old.`);
}
private sendEmail(): void {
console.log(`Email sent to ${this.email}`);
}
// Protected method
protected getAge(): number {
return this.age;
}
}
class Employee extends Person {
// Inherited properties can be accessed in subclasses
showAge(): void {
console.log(`Age: ${this.getAge()}`);
}
}
// Creating an instance of the Person class
const person = new Person('John', 30, 'john@example.com');
// Accessing public properties and methods
person.name = 'Jane';
person.introduce();
// Accessing private and protected members will result in an error
// person.age; // Error: Property 'age' is private
// person.email; // Error: Property 'email' is protected
// person.sendEmail(); // Error: Property 'sendEmail' is private
// Creating an instance of the Employee class
const employee = new Employee('Alice', 25, 'alice@example.com');
// Accessing protected method through subclass
employee.showAge(); // Output: Age: 25
// employee.getAge(); // Error: Property 'getAge' is protected