AlgoMaster Logo

Classes and Objects

Ashish

Ashish Pratap Singh

At the heart of OOP lie two fundamental concepts: classes and objects.

They are the foundation on which every OOP-based language like Java, Python, C++, C#, or TypeScript is built.

1. What is a Class?

A class is a blueprint, template, or recipe for creating objects. It defines what an object will contain (its data) and what it will be able to do (its behavior).

A class is not an object itself, it’s a template used to create many objects with similar structure but independent state.

Key Characteristics of a Class:

  • It groups related data (attributes) and actions (methods) together.
  • Defines attributes to represent the state or data of an object.
  • Defines methods (functions inside a class) to represent the behavior or actions the object can perform.

Example: Class Blueprint

Let’s define a simple Car class with essential attributes and methods that any Car object will have.

The following diagram and code show the blueprint for a Car:

Code:

This Car class defines what every car object should look like and what it can do.

2. What is an Object?

An object is an instance of a class. It’s a real-world manifestation of the class blueprint, something you can interact with, store data in, and invoke methods on.

When you create an object, you’re essentially saying:

“Take this blueprint (class) and build one actual thing (object) out of it.”

Each object:

  • Has its own copy of the data defined in the class.
  • Shares the same structure and behavior as defined by the class.
  • Operates independently of other objects.

Creating Objects

Let’s now create a few car objects using our Car class.

Code:

Output:

Here, corolla and mustang are objects of the Car class. They have their own brand , model , and speed fields and can use methods defined in the class.

Classes and objects are powerful when you need to model complex structures or real-world entities. But what if you simply want to define a fixed set of constants, values that rarely change and for which you only ever need one instance of each?

That's where Enums come in. Lets explore them next.