What are Classes and Objects in Typescript
Classes and Objects in TypeScript
In TypeScript, classes serve as blueprints for creating objects. They encapsulate data (properties) and behavior (methods) related to a specific concept or entity.
Classes:
Defined using the class keyword and a name (e.g., class Person {}).
Can have properties (variables representing data) and methods (functions defining behavior).
Properties and methods can be public (accessible from anywhere), private (accessible only within the class), or protected (accessible within the class and subclasses).
Example:
TypeScript
class Person {
// Public property
name: string;
// Private constructor (cannot be called directly)
private constructor(name: string) {
this.name = name;
}
// Public method
greet(): void {
console.log(`Hello, my name is ${this.name}`);
}
// Public static method (not associated with an instance)
static create(name: string): Person {
return new Person(name);
}
}
Objects:
Created using the new keyword with the class name (e.g., const person = new Person("Alice")).
Represent instances of a class with access to its properties and methods.
Each object has its own set of property values and can invoke methods independently.
Example:
TypeScript
const alice = Person.create("Alice");
alice.greet(); // Output: "Hello, my name is Alice"
Inheritance:
Classes can inherit from other classes (called base classes) using the extends keyword.
Inherited classes get access to properties and methods of the base class, and can also add their own.
Example:
TypeScript
class Employee extends Person {
company: string;
constructor(name: string, company: string) {
super(name); // Call base class constructor
this.company = company;
}
introduce(): void {
console.log(`Hi, I'm ${this.name} from ${this.company}`);
}
}
const bob = new Employee("Bob", "Acme Corp");
bob.introduce(); // Output: "Hi, I'm Bob from Acme Corp"
Key Advantages:
Code organization: Classes group related data and behavior, promoting modularity and reusability.
Encapsulation: Data and implementation details are hidden within the class, improving maintainability and security.
Polymorphism: Subclasses can override inherited methods, providing flexible behavior based on the object type.
By effectively using classes and objects, you can create well-structured and maintainable TypeScript applications, organizing your code in a clear and reusable manner.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.