Classes & Objects

OOP: 'Classes' & 'Objects'

* A class is a blueprint defining properties and behaviors. Objects are instances of classes, representing specific entities with unique data and actions.

What is 'classes' & 'objects'?

A class is a blueprint for creating objects. It defines the data and behavior that objects of that type will have. An object, on the other hand, is an instance of a class. It represents a specific entity in your program with its own state (data) and behavior (methods).

Let's create and break down a program from the syntax which is provided on the OOP page:

cs Copy Code
using System;

class Car {
// Property to store the make of the car
    public string? Make { get; set; } 
// Property to store the model of the car
    public string? Model { get; set; } 

    public void Drive() { 
// Method to simulate driving the car
        Console.WriteLine("Driving...");
    }
}

class Program {
    static void Main(string[] args) {
        Car myCar = new Car(); // Creating a new instance of the Car class
        myCar.Make = "Toyota"; // Setting the make of the car to "Toyota"
        myCar.Model = "Camry"; // Setting the model of the car to "Camry"
        myCar.Drive(); // Calling the Drive method of the car object
    }
}
Output:
Driving...

Explanation:

1. Class Definition (Car): The program starts by defining a class named 'Car'. This class has two public properties: 'Make' and 'Model', which are strings representing the make and model of the car, respectively. Additionally, it has a public method 'Drive()' that simply prints "Driving..." to the console.

2. Object Creation: After defining the 'Car' class, the program creates an object of type 'Car' named 'myCar' using the 'new' keyword. This object is an instance of the 'Car' class and has its own memory allocation.

3. Setting Properties: Following object creation, the program sets the properties of the 'myCar' object. It sets the 'Make' property to "Toyota" and the 'Model' property to "Camry" using dot notation.

4. Method Invocation: Finally, the program calls the 'Drive()' method on the 'myCar' object. This method call results in the message "Driving..." being printed to the console, simulating the action of driving the car.

In summary, this program demonstrates the creation of a 'Car' class with properties to represent car make and model, and a method to simulate driving. It then creates an instance of this class, sets its properties, and invokes its method to simulate driving the car.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.