TypeScript

12.Understanding Classes and Objects in TypeScript

Understanding Classes and Objects in TypeScript

TypeScript, being a superset of JavaScript, enhances JavaScript by introducing support for object-oriented programming (OOP) features like classes, objects, inheritance, and polymorphism. While JavaScript doesn’t support OOP directly, TypeScript makes it easier to work with objects and classes by providing the tools necessary for object-oriented design. This chapter will cover everything you need to know about classes, objects, and their various features in TypeScript.

If you’re coming from an object-oriented background in languages like Java, C++, or C#, you’ll find this chapter easy to understand. However, if you’re new to OOP, make sure to pay attention and follow along with the examples!


What is a Class?

A class in TypeScript is a blueprint for creating objects with shared properties and methods. It defines the common behavior and attributes that its objects (instances) will have. A class encapsulates data and behavior into one structure.

What is an Object?

An object is an instance of a class. Once a class is defined, you can create multiple objects (instances) from that class. Each object will have the same properties and methods as the class but with different values.


Creating Classes in TypeScript

To define a class in TypeScript, you use the class keyword, followed by the class name, and curly braces {} to define the properties and methods of the class.

Syntax for Creating a Class:

class ClassName {
// Class properties (data members)
// Constructor (if needed)
// Methods (functions)
}

Naming Conventions for Classes:

  • Class names should be written in PascalCase (e.g., Animal).

  • Class names cannot start with a number, contain special characters, or have spaces.


Example 1: Basic Class in TypeScript

Here is a simple example of a class with properties and a method:

class Animal {
color: string; // Property
constructor(color: string) {
this.color = color; // Assigning the color property value
}walk(): void {
console.log(“Color of animal is: “ + this.color);
}
}

const animal = new Animal(“White”); // Creating an instance of the Animal class
animal.walk(); // Calling the method on the object

Explanation:

  • We have created a class Animal with a property color and a method walk().

  • The constructor is used to initialize the class with a value for color.

  • We created an instance of the Animal class and called its walk method.

Output:

Color of animal is: White

Creating Instance Objects

To create an instance of a class and access its properties or methods, you use the new keyword.

Syntax:

let object_name = new ClassName(arguments);

In the above example, we created an instance of the Animal class using the new keyword and passed an argument "White" to the constructor.


Example 2: More Complex Class with Properties and Methods

Let’s expand on the previous example with multiple properties and methods:

class Animals {
color: string;
size: string;
constructor(size: string = ‘Medium’, color: string = ‘Brown’) {
this.size = size;
this.color = color;
}walk(): void {
console.log(`The animal is: ${this.size} and ${this.color}`);
}
}

const animal1 = new Animals(“Big”);
console.log(“Reading attribute value color as: “ + animal1.color);
animal1.walk();

const animal2 = new Animals(“Small”, “White”);
animal2.walk();
console.log(“Reading attribute value color as: “ + animal2.color);

Explanation:

  • The Animals class has two properties: size and color.

  • The constructor allows you to initialize these properties when creating an object. Default values are provided if no values are passed.

  • We create two objects, animal1 and animal2, each with different values.

Output:

Reading attribute value color as: Brown
The animal is: Big and Brown
The animal is: Small and White
Reading attribute value color as: White

Class Inheritance

TypeScript supports inheritance, where one class (child class) can inherit properties and methods from another class (parent class). The extends keyword is used for inheritance.

Example 3: Inheritance in TypeScript

class Animal {
name: string;
constructor(name: string) {
this.name = name;
}speak(): void {
console.log(this.name + ” makes a noise.”);
}
}

class Dog extends Animal {
constructor(name: string) {
super(name); // Call the parent class constructor
}

speak(): void {
console.log(this.name + ” barks.”);
}
}

const dog = new Dog(“Buddy”);
dog.speak(); // Output: Buddy barks.

Explanation:

  • The Dog class extends the Animal class and inherits the name property.

  • The speak method is overridden in the Dog class to provide a more specific implementation.

Output:

Buddy barks.

Method Overriding

Method overriding allows a subclass to provide its own implementation of a method that is already defined in the parent class.

Example 4: Method Overriding

class Training {
teach(): void {
console.log("Teach() from classroom...");
}
}
class OnlineTraining extends Training {
teach(): void {
super.teach(); // Call parent class method
console.log(“Teaching Online”);
}
}const onlineCourse = new OnlineTraining();
onlineCourse.teach();

Explanation:

  • The OnlineTraining class overrides the teach method from the Training class.

  • The super.teach() inside the child class calls the method from the parent class before adding its own behavior.

Output:

Teach() from classroom...
Teaching Online

Static Members

Static members belong to the class itself rather than to instances of the class. They are accessed directly using the class name, without needing to create an instance.

Example 5: Static Members in a Class

class Employee {
static companyName: string = "TechCorp";
static getCompanyName(): string {
return Employee.companyName;
}
}console.log(Employee.getCompanyName()); // Output: TechCorp

Explanation:

  • The companyName property is static, so it belongs to the class, not to an individual instance.

  • We access the static property directly using the class name Employee.

 

🔐 Access Specifiers in TypeScript (with WiFi Example)

Access specifiers determine how class members are visible to other parts of your code. TypeScript supports three access modifiers:

  • public: Accessible from anywhere – like Airport WiFi

  • protected: Accessible within the class and its subclasses – like Office WiFi (only for employees)

  • private: Accessible only within the class – like Personal Mobile Hotspot

 


Access Specifiers

class WiFiAccess {
  public airportWiFi: string = "Open WiFi - Everyone can connect";
  protected officeWiFi: string = "Office WiFi - Employees only";
  private personalHotspot: string = "Private Hotspot - Only I can access";

  showAccess(): void {
    console.log("Public:", this.airportWiFi);
    console.log("Protected:", this.officeWiFi);
    console.log("Private:", this.personalHotspot);
  }
}

class OfficeUser extends WiFiAccess {
  accessWiFi(): void {
    console.log("Accessing:", this.airportWiFi); // ✅ Public
    console.log("Accessing:", this.officeWiFi);  // ✅ Protected
    // console.log(this.personalHotspot); // ❌ Error: private
  }
}

const user = new WiFiAccess();
console.log(user.airportWiFi); // ✅ Public
// console.log(user.officeWiFi); // ❌ Error: protected
// console.log(user.personalHotspot); // ❌ Error: private
user.showAccess(); // ✅ Can access all within the class

 

Explanation:

  • The sname property is public, so it can be accessed outside the class.

  • The roll property is private, so it can only be accessed within the PrivateData class.


Conclusion

In this chapter, we’ve covered the basics of classes and objects in TypeScript, including:

  • Class Declaration: Creating classes with properties, methods, and constructors.

  • Object Creation: Instantiating objects from classes and accessing their members.

  • Inheritance: Extending a class to create subclasses.

  • Method Overriding: Overriding methods from parent classes in child classes.

  • Static Members: Using static members that belong to the class itself.

  • Access Specifiers: Controlling the visibility of class members with public, private, and protected.

 

Assignment 1: Create a Basic Class

  • Create a class Car with a single property brand (string).

  • Create a constructor to initialize brand.

  • Add a method displayBrand() to print the brand.

  • Create an object of the class and call the method.


Assignment 2: Add Multiple Properties

  • Create a class Laptop with properties: brand (string) and price (number).

  • Create a constructor to initialize both properties.

  • Add a method displayInfo() to display brand and price.

  • Create two different objects with different values and call the method on each.


Assignment 3: Use Default Values in Constructor

  • Create a class Book with properties: title (string) and author (string).

  • Set default values for both properties inside the constructor.

  • Allow passing custom values as well when creating objects.

  • Create two objects: one with default values, one with custom values.


Assignment 4: Create Objects Dynamically

  • Create a class Mobile with model and price properties.

  • Create a constructor to initialize these properties.

  • Create five different objects dynamically with different models and prices.

  • Display their information using a method.


Assignment 5: Inheritance (Extending a Class)

  • Create a parent class Vehicle with a property name and a method move().

  • Create a child class Bike that extends Vehicle.

  • Override the move() method in Bike to print a different message.

  • Create an object of Bike and call the move() method.


Assignment 6: Practice Method Overriding

  • Create a parent class Account with a method getAccountType() that prints "Generic Account".

  • Create a subclass SavingAccount that overrides getAccountType() to print "Saving Account".

  • Create an object of SavingAccount and call getAccountType().


Assignment 7: Static Members

  • Create a class University with a static property universityName.

  • Create a static method getUniversityName().

  • Access and print the static property without creating an instance.


Assignment 8: Access Specifiers

  • Create a class Student with:

    • public property name

    • private property id

  • Create a method displayStudent() inside the class that prints both name and id.

  • Create an object of Student and call displayStudent().


Assignment 9: Protected Access Specifier

  • Create a class Employee with a protected property employeeId.

  • Create a subclass Manager that inherits Employee.

  • Inside Manager, create a method showEmployeeId() that prints employeeId.

  • Create an object of Manager and call showEmployeeId().


Assignment 10: Real-Life Mini Project (Combination of All Topics)

  • Create a class Person with name, age, and a method introduce().

  • Create a subclass Teacher that extends Person and adds a property subject.

  • Override the introduce() method in Teacher to include the subject.

  • Add a static property schoolName and static method getSchoolName().

  • Create objects of Person and Teacher.

  • Access the static method directly from the class.

Leave a Reply

Your email address will not be published. Required fields are marked *