Classes and Objects

Classes and objects are fundamental concepts in object-oriented programming (OOP). They allow you to model real-world entities and create reusable, modular code.

What are Classes?

A class is a blueprint or a template for creating objects. It defines the properties (data members or attributes) and behaviors (member functions or methods) that objects of that class will have. Think of a class as the design for a house; it specifies how many rooms it has, what materials to use, etc.

What are Objects?

An object is an instance of a class. When you create an object, you are creating a concrete entity based on the class blueprint. Each object has its own unique set of data members, but shares the same methods defined by its class. In our house analogy, an object would be an actual house built from the blueprint.

Defining a Class

Let's consider a simple example of a Car class in a C#-like syntax.


public class Car
{
    // Properties (Attributes)
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
    public string Color { get; set; }

    // Constructor
    public Car(string make, string model, int year, string color)
    {
        Make = make;
        Model = model;
        Year = year;
        Color = color;
    }

    // Methods (Behaviors)
    public void StartEngine()
    {
        Console.WriteLine($"{Color} {Make} {Model}'s engine started.");
    }

    public void Accelerate()
    {
        Console.WriteLine($"{Make} {Model} is accelerating.");
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Car: {Year} {Color} {Make} {Model}");
    }
}
            

Creating and Using Objects

Once a class is defined, you can create objects (instances) of that class. This is typically done using the new keyword, followed by the class name and any necessary constructor arguments.


// Create an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2022, "Blue");

// Access properties of the object
Console.WriteLine($"My car is a {myCar.Color} {myCar.Make}."); // Output: My car is a Blue Toyota.

// Call methods of the object
myCar.StartEngine(); // Output: Blue Toyota Camry's engine started.
myCar.Accelerate();  // Output: Toyota Camry is accelerating.
myCar.DisplayInfo(); // Output: Car: 2022 Blue Toyota Camry

// Create another object of the same class
Car anotherCar = new Car("Honda", "Civic", 2023, "Red");
anotherCar.DisplayInfo(); // Output: Car: 2023 Red Honda Civic
            

Tip:

Each object created from a class is independent. Changes to one object's properties do not affect other objects of the same class.

Key Concepts Related to Classes and Objects

Important:

Understanding classes and objects is crucial for building robust, scalable, and maintainable applications using object-oriented paradigms.

In the next tutorial, we will explore how classes can inherit properties and behaviors from other classes through inheritance.