Classes and Objects
Classes and Objects
Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries — we'll start from the basics.
Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics, such as inheritance, polymorphism, and encapsulation.
Defining a Class
In TypeScript, a class is defined using the class keyword, just like in many other languages. However, TypeScript allows you to specify types for class properties and constructor parameters, enabling compile-time type checking and reducing runtime errors.
Here's a simple example:
In this snippet, we define a Person class with two properties: name (of type string) and age (of type number). The constructor parameters are also annotated with their respective types. TypeScript will check at compile time that only the correct types are used when creating instances of this class.
What is an Object?
An object is an instance of a class. It represents a specific example of the class and holds the characteristics that define the class.
Objects have three main characteristics:
- State: The data or attributes of the object. In the
Personclass, thenameandageare the object's state. - Behavior: The methods and functions that the object can perform. In the
Personclass, thedisplaymethod is mentioned here as an example of behavior, and it will be implemented later in this lesson. - Identity: A unique identifier distinguishes the object from others, even if they have the same state. This is handled by the memory address in the runtime environment.
An object is thus a concrete instance of a class that includes state, behavior, and identity.
Using Constructors
