Explain that question "What is a class in OOP?". Use TypeScript for your explanations
- User
Explain that question "What is a class in OOP?". Use TypeScript for your explanations
- Assistant
Explain that question "What is a class in OOP?". Use TypeScript for your explanations
A class in Object-Oriented Programming (OOP) is a blueprint for creating objects. It encapsulates data for the object (in the form of properties) and methods to manipulate that data. Classes promote code reusability, modularity, and abstraction, allowing developers to model real-world entities and their interactions within software.
TypeScript, being a superset of JavaScript, provides robust support for OOP concepts, including classes. Let’s explore what a class is in OOP using TypeScript through examples and explanations.
In TypeScript, you can define a class using the class keyword, followed by the class name and a block containing its properties and methods.
class Person {
// Properties
name: string;
age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method
greet(): void {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
Explanation:
name and age are properties of the Person class.constructor method initializes new objects with the provided name and age.greet is a method that logs a greeting message to the console.Creating an Instance:
const person1 = new Person("Alice", 30);
person1.greet(); // Output: Hello, my name is Alice and I'm 30 years old.
TypeScript provides access modifiers to control the visibility of class members:
public: Accessible from anywhere (default).private: Accessible only within the class.protected: Accessible within the class and its subclasses.class Person {
public name: string;
private age: number;
protected address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
public greet(): void {
console.log(`Hello, my name is ${this.name}.`);
}
private getAge(): number {
return this.age;
}
}
Usage:
const person1 = new Person("Bob", 25, "123 Main St");
console.log(person1.name); // Accessible: Output: Bob
// console.log(person1.age); // Error: Property 'age' is private
person1.greet(); // Accessible: Output: Hello, my name is Bob.
// person1.getAge(); // Error: Property 'getAge' is private
Classes can inherit from other classes, allowing for hierarchical classifications and reuse of code.
class Employee extends Person {
public employeeId: number;
constructor(name: string, age: number, address: string, employeeId: number) {
super(name, age, address); // Call the constructor of the parent class
this.employeeId = employeeId;
}
public work(): void {
console.log(`${this.name} is working.`);
}
// Overriding a method from the parent class
public greet(): void {
console.log(`Hello, my name is ${this.name}, and my employee ID is ${this.employeeId}.`);
}
}
Usage:
const employee1 = new Employee("Charlie", 28, "456 Elm St", 101);
employee1.greet(); // Output: Hello, my name is Charlie, and my employee ID is 101.
employee1.work(); // Output: Charlie is working.
Explanation:
Employee extends Person, inheriting its properties and methods.super keyword is used to call the parent class's constructor.greet method is overridden to provide a more specific implementation.TypeScript allows defining getters and setters for class properties, enabling controlled access and modification.
class Rectangle {
private _width: number;
private _height: number;
constructor(width: number, height: number) {
this._width = width;
this._height = height;
}
// Getter for area
get area(): number {
return this._width * this._height;
}
// Getter and Setter for width
get width(): number {
return this._width;
}
set width(value: number) {
if (value > 0) {
this._width = value;
} else {
throw new Error("Width must be positive.");
}
}
// Getter and Setter for height
get height(): number {
return this._height;
}
set height(value: number) {
if (value > 0) {
this._height = value;
} else {
throw new Error("Height must be positive.");
}
}
}
Usage:
const rect = new Rectangle(10, 20);
console.log(rect.area); // Output: 200
rect.width = 15;
rect.height = 25;
console.log(rect.area); // Output: 375
// rect.width = -5; // Error: Width must be positive.
Explanation:
_width and _height are private properties.get and set allow controlled access to these properties.area is a computed property using a getter.Classes can have static properties and methods that belong to the class itself rather than any instance.
class MathUtils {
static pi: number = 3.14159;
static calculateCircumference(radius: number): number {
return 2 * MathUtils.pi * radius;
}
}
Usage:
console.log(MathUtils.pi); // Output: 3.14159
console.log(MathUtils.calculateCircumference(5)); // Output: 31.4159
Explanation:
pi is a static property.calculateCircumference is a static method.MathUtils without creating an instance.Abstract classes cannot be instantiated directly and are meant to be subclassed. They can contain abstract methods that must be implemented by subclasses.
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("The animal moves.");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Woof! Woof!");
}
}
class Cat extends Animal {
makeSound(): void {
console.log("Meow!");
}
}
Usage:
// const animal = new Animal(); // Error: Cannot create an instance of an abstract class
const dog = new Dog();
dog.makeSound(); // Output: Woof! Woof!
dog.move(); // Output: The animal moves.
const cat = new Cat();
cat.makeSound(); // Output: Meow!
cat.move(); // Output: The animal moves.
Explanation:
Animal is an abstract class with an abstract method makeSound.Dog and Cat extend Animal and provide implementations for makeSound.While not strictly a part of classes, interfaces in TypeScript are often used alongside classes to define contracts that classes must adhere to.
interface Shape {
area(): number;
}
class Circle implements Shape {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
Usage:
const circle = new Circle(5);
console.log(circle.area()); // Output: 78.53981633974483
Explanation:
Shape interface defines a contract with the area method.Circle implements Shape, ensuring it provides an area method.In OOP, a class is a fundamental building block that encapsulates data and behaviors related to a specific entity. TypeScript enhances this concept with strong typing, access modifiers, inheritance, abstract classes, and interfaces, allowing developers to write robust and maintainable code. By using TypeScript's class features, you can effectively model real-world scenarios, enforce contracts, and promote code reuse in your applications.
Not yet included in a published release.