Creating Classes And Objects
Lesson 3.2: Creating Classes and Objects
In the previous lesson, you learned about the fundamental concepts of OOP. Now, it's time to put those concepts into practice by creating your own classes and objects in C#.
Classes: The Blueprints
Remember, a class is like a blueprint for creating objects. It defines the properties (data) and methods (behaviors) that objects of that class will have.
Here's the basic syntax for defining a class:
C#
class ClassName
{
// Properties (fields)
// Methods
}
Properties:
These represent the characteristics or attributes of an object.
In C#, you often use auto-implemented properties for simplicity:
C#
public string Name { get; set; }
public int Age { get; set; }
Methods:
Methods define the actions that an object can perform.
They often take parameters (input values) and can return results.
C#
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
Objects: The Real Things
An object is a concrete instance of a class. It represents a specific thing with its own unique data.
To create an object, you use the new keyword followed by the class name and parentheses:
C#
ClassName myObject = new ClassName();
You can then access the properties and methods of the object using dot notation (objectName.propertyName or objectName.methodName()).
Example: Creating a Person Class and Object
C#
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 30;
person1.Introduce(); // Output: Hello, my name is Alice and I am 30 years old.
Person person2 = new Person() { Name = "Bob", Age = 25 };
person2.Introduce(); // Output: Hello, my name is Bob and I am 25 years old.
}
}
Key Points
Classes: Blueprints for creating objects.
Objects: Instances of classes with their own data.
Properties: Represent the characteristics of an object.
Methods: Define the actions that an object can perform.
new Keyword: Used to create new objects.
Hands-On Exercise:
Create a Car class with properties like Make, Model, and Year.
Add a method Start() that prints a message indicating the car is starting.
Create a few Car objects and set their properties.
Call the Start() method on each object to see the result.
This practical exercise will solidify your understanding of classes and objects in C#!