Classes and Objects
In C#, classes are used to define objects. An object is an instance of a class that can have attributes (variables) and behaviors (methods).
To define a class, you need to specify the class name and its members. The members can include variables, methods, properties, events, and more.
Here's an example of defining a Car
class:
1using System;
2
3class Car
4{
5 // Class variables
6 public string make;
7 public string model;
8 public int year;
9
10 // Constructor
11 public Car(string make, string model, int year)
12 {
13 this.make = make;
14 this.model = model;
15 this.year = year;
16 }
17
18 // Method
19 public void Drive()
20 {
21 Console.WriteLine("The " + make + " " + model + " is driving.");
22 }
23}
In this example, we define a Car
class with three attributes (make
, model
, and year
) and a Drive
method. The class constructor is used to initialize the attributes when creating an instance of the class.
To use the Car
class, you need to create an instance of it. Here's an example:
1// Create an instance of the Car class
2Car myCar = new Car("Ford", "Mustang", 2021);
3
4// Access the attributes and methods of the Car class
5Console.WriteLine("Make: " + myCar.make);
6Console.WriteLine("Model: " + myCar.model);
7Console.WriteLine("Year: " + myCar.year);
8
9myCar.Drive();
In this example, we create a myCar
object of type Car
and set its attributes. Then, we access the attributes and call the Drive
method of the myCar
object.
Classes and objects are fundamental concepts in object-oriented programming and serve as the building blocks for creating complex systems. They allow you to model real-world entities and define their properties and behaviors.
Next, we will explore the concept of inheritance and how it enables code reuse and extension in object-oriented programming.
xxxxxxxxxx
}
using System;
class Car
{
// Class variables
public string make;
public string model;
public int year;
// Constructor
public Car(string make, string model, int year)
{
this.make = make;
this.model = model;
this.year = year;
}
// Method
public void Drive()
{
Console.WriteLine("The " + make + " " + model + " is driving.");
}
}
class Program
{
static void Main()
{
// Create an instance of the Car class