Constructors And Methods In Classes

Lesson 3.3: Constructors and Methods Within Classes


In the previous lesson, you learned how to create classes and objects. Now, let's dive deeper into the building blocks of classes: constructors and methods.


Constructors: Initializing Objects


A constructor is a special method that is automatically called when you create a new object of a class.

Its primary purpose is to initialize the object's properties (set their initial values) and perform any necessary setup.

Constructors have the same name as their class and don't have a return type (not even void).

Types of Constructors


Default Constructor:


If you don't define any constructors, C# automatically provides a default constructor.

The default constructor initializes all properties to their default values (e.g., 0 for numbers, null for strings).

Parameterized Constructor:


You can create constructors that take parameters, allowing you to pass in values to initialize the object's properties when it's created.

C#

class Car

{

    public string Make { get; set; }

    public string Model { get; set; }


    // Parameterized constructor

    public Car(string make, string model)

    {

        Make = make;

        Model = model;

    }

}


// Creating an object with the parameterized constructor

Car myCar = new Car("Toyota", "Camry");

Methods: Actions and Behaviors


Methods define the actions that an object can perform. They are functions that belong to a class.

Methods often take input parameters and may return a value.

Here's the general syntax:

C#

<return type> <method name> (<parameters>)

{

    // Method body (code to execute)

}

Example:

C#

class Dog

{

    public string Name { get; set; }


    public void Bark() 

    {

        Console.WriteLine($"{Name} says Woof!");

    }

}


Dog myDog = new Dog() { Name = "Buddy" };

myDog.Bark(); // Output: Buddy says Woof!


Overloading Methods


You can create multiple methods with the same name in a class, as long as their parameter lists are different (number of parameters or their types).

This is called method overloading and allows you to provide different versions of a method for different scenarios.

C#

class Calculator

{

    public int Add(int a, int b)

    {

        return a + b;

    }


    public double Add(double a, double b)

    {

        return a + b;

    }

}

Key Points


Constructors: Initialize objects when they are created.

Methods: Define the actions objects can take.

Overloading: Create multiple methods with the same name but different parameters.

Hands-On Exercise:


Create a BankAccount class with properties for AccountNumber, Balance, and OwnerName.

Create a constructor that takes the account number and owner name as parameters and sets the initial balance to 0.

Add methods to Deposit money, Withdraw money (ensuring the balance doesn't go negative), and GetBalance.

Create a BankAccount object and test your methods.

Course Syllabus