TypeScript / TypeScript Classes and Object-Oriented Programming
Understanding Access Modifiers in Classes
This tutorial will delve into access modifiers in TypeScript classes. We will learn about public, private, and protected modifiers and their uses.
Section overview
5 resourcesExplores object-oriented principles in TypeScript, including classes, inheritance, and access modifiers.
Understanding Access Modifiers in Classes
1. Introduction
In this tutorial, we aim to understand access modifiers in TypeScript classes. We will explore public, private, and protected modifiers, their features, and practical uses.
By the end of this guide, you will be able to:
- Understand and use different access modifiers
- Develop and design TypeScript classes more effectively
Prerequisites: Basic knowledge of TypeScript and object-oriented programming concepts is beneficial.
2. Step-by-Step Guide
Access modifiers in TypeScript are used to set accessibility boundaries for properties, methods, and other members of a class. There are three types of access modifiers: public, private, and protected.
Public: This is the default modifier and accessible anywhere without any restrictions.
Private: These members are only accessible within the class that defines them.
Protected: This is similar to private, but these members can also be accessed within subclasses.
Best Practices and Tips
- Use the
privatemodifier to hide implementation details and prevent external manipulation. - The
protectedmodifier is useful when you're writing a class that's intended to be subclassed. - Even though
publicis the default, explicitly labeling public members can make your code more readable.
3. Code Examples
Example 1: Public Modifier
class Car {
public make: string; // This can be accessed anywhere
constructor(make: string) {
this.make = make;
}
}
const myCar = new Car('Toyota');
console.log(myCar.make); // Outputs: Toyota
In this example, make is a public property of the Car class, meaning it can be accessed directly from an instance of the class (myCar).
Example 2: Private Modifier
class Car {
private miles: number; // This can only be accessed within the Car class
constructor() {
this.miles = 0;
}
drive(distance: number) {
this.miles += distance;
}
getMiles() {
return this.miles;
}
}
const myCar = new Car();
myCar.drive(100);
console.log(myCar.getMiles()); // Outputs: 100
// console.log(myCar.miles); would cause an error
In this example, miles is a private property. It can't be accessed directly from myCar; instead, we provide a getMiles method to access it.
4. Summary
We've learned about access modifiers and how they can help us manage the accessibility of our class members. Public, private, and protected modifiers each have their own use cases and should be chosen appropriately to design robust classes.
For the next steps, practice using these modifiers in your own classes. You can also explore TypeScript's official documentation for more concepts.
5. Practice Exercises
Exercise 1: Create a Person class with public name, private age, and a public method getAge which returns age.
Exercise 2: Extend the Person class to create a Student class. Add a protected grades property and a method to access it.
Solutions:
Exercise 1:
class Person {
public name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getAge() {
return this.age;
}
}
Exercise 2:
class Student extends Person {
protected grades: number[];
constructor(name: string, age: number, grades: number[]) {
super(name, age);
this.grades = grades;
}
getGrades() {
return this.grades;
}
}
Remember, the key to understanding is consistent practice. Keep experimenting with different scenarios and the application of these modifiers.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article