Mastering OOP: Unveiling the Power of Constructors for Efficient Code Creation and Optimization

mzunairtariq

M ZUNAIR TARIQ

Posted on January 21, 2024

Mastering OOP: Unveiling the Power of Constructors for Efficient Code Creation and Optimization

Understanding Constructors in Object-Oriented Programming: A Comprehensive Guide to Creating Efficient Code. Explore the fundamental concepts of Object-Oriented Programming (OOP), with a specific emphasis on constructors, which play a crucial role in establishing the underlying structure of your code. Regardless of your level of experience as a developer, explore the ways in which these very effective techniques improve the process of creating objects, simplify code, and expand your programming skills. Embark on a quest with us to become proficient in constructors and unleash their capacity for efficient, adaptable, and comprehensible software architecture.

What is the definition of the constructor?

A constructor is a specific method within a class that is responsible for initializing the variables of that class.

  • A constructor method shares the same name as the class it belongs to and is a method that does not return a value.

  • A constructor is necessary for every class in order to instantiate an object of that class.

Code example in C#

using System;

class MyClass
{
    // Constructor
    public MyClass()
    {
        Console.WriteLine("Constructor called!");
    }

    // Other methods or properties can be defined here
}

class Program
{
    static void Main()
    {
        // Creating an instance of MyClass will automatically call the constructor
        MyClass myObject = new MyClass();

        // Rest of your program logic
    }
}

Enter fullscreen mode Exit fullscreen mode

Responsibilities regarding the constructor:

  • It's the responsibility of a programmer to define a constructor under his class, and if he fails to do so, on behalf of the programmer an implicit constructor gets defined in that class by the compiler.

  • Implicitly defined constructors are also known as default constructors. The default constructor is a constructor that doesn't accept parameters.

Implicit public

  • Implicitly defined constructors are Public.
  • We can also define a constructor under the class, and if we define it, We can call it an explicit constructor, and an explicit constructor can be parameter-less or parameterized as well.
// Syntax of the Constructor:
[<modifiers>] <Name>( [<parameter list>] )
{
    //Statements
}
Enter fullscreen mode Exit fullscreen mode

Here's a thing to note:

  • The constructor that was defined implicitly is even called explicitly.

Implicit constructor is called explicitly

Types of constructors:

  • Default or parameter-less constructor

    • If a constructor method doesn't take any parameters, then we call that as a default or parameter-less constructor. These constructors can be defined explicitly by a programmer, or else they will default implicitly, provided there is no explicit constructor under the class.
  • Parameterized constructor

    • If a constructor method is defined with any parameters, we call that as a parameterized constructor, and these constructors can be defined by the programmers only, but it can never be defined implicitly.

Code example in C#

using System;

class Person
{
    // Properties
    public string Name { get; set; }
    public int Age { get; set; }

    // Parameterized Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Method to display information
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

class Program
{
    static void Main()
    {
        // Creating an instance of Person with a parameterized constructor
        Person person1 = new Person("John Doe", 25);

        // Displaying information using the method
        person1.DisplayInfo();

        // Creating another instance with different values
        Person person2 = new Person("Jane Smith", 30);

        // Displaying information for the second person
        person2.DisplayInfo();
    }
}

Enter fullscreen mode Exit fullscreen mode
  • Copy constructor
    • A copy constructor in C# is a specialized constructor within a class that takes an instance of the same class as a parameter and creates a new object with the same state as the provided instance. It facilitates the duplication of object data, ensuring that the new object's properties match those of the source object, allowing for efficient object copying and initialization.

Code example in C#

Copy Constructor Demo in C# .NET

  • Static constructor
    • A static constructor in C# is a special constructor declared with the static keyword and is called automatically before any static members are accessed or any static methods are called. It is used to initialize static members or perform one-time setup tasks for a class. Unlike instance constructors, a static constructor doesn't take any parameters and is invoked only once during the lifetime of the application, ensuring that static members are initialized before they are used.
    • If a class contains any static variables, then only implicit static constructors will be present, or else we need to define them explicitly, whereas non-static constructors will be implicitly defined in every class (except static classes), provided we do not define them explicitly.
    • Static constructors are responsible for initializing static variables, and these constructors are never called explicitly; they are implicitly called, and moreover, these constructors are first to execute under a class.
    • Static constructors can't be parameterized, so overloading static constructors is not possible.
  1. Implicit Static Constructors:

    • If a class contains any static variables or static members, the C# compiler implicitly adds a static constructor to the class.
    • This static constructor is automatically called before any static members are accessed or any static methods are called within the class.
    • You don't need to define the static constructor explicitly; it is added by the compiler.
  2. Implicit Non-Static Constructors:

    • For non-static classes (regular classes), if you don't define any constructors explicitly, the C# compiler implicitly adds a default parameter-less constructor to the class.
    • This default constructor is automatically called when an instance of the class is created using the new keyword.
    • If you define any non-default constructors, the compiler does not add the default constructor unless you explicitly include it in your code.

Here's a simple example:

public class MyClass
{
    // Implicit non-static default constructor
    public MyClass()
    {
        // Initialization code (if any)
    }

    // Implicit static constructor (if there are static members)
    static MyClass()
    {
        // Static initialization code (if any)
    }

    // Other members of the class
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the default constructor is implicitly added because we didn't define any constructors explicitly. If there were static members, the static constructor would also be implicitly added.

Why are constructors needed in our class?

Every class requires a constructor to be present if we want to create an instance of that class. Every class contains an implicit constructor, if not defined explicitly, and with the help of that implicit constructor, an instance of the class can be created.
 

What is the need for defining a constructor explicitly again?

  • Implicit constructors of a class will initialize variables of that class with the same value even if we create multiple instances of that class.
  • If we define constructors explicitly with parameters, then we get a change in initializing the fields or variables of the class with a new value every time we are going to create an instance of that class.
  • When ever we define a class, first identify whether the class variables require some values to execute, and if they are required, then define a constructor explicitly and pass values through that constructor, so every time the instance of the class is created, we get a chance of passing new values.

Note: Generally, every class requires some values for execution, and the values that are required for a class to execute are always sent to that class by using the constructor only.

Static Constructors vs. Non-Static Constructors:

  • If a constructor is explicitly declared by using a static modifier, we call that constructor a static constructor, whereas the rest of the others are non-static constructors only.
  • Constructors are responsible for initializing fields or variables of a class; static fields are initialized by static constructors, and non-static fields are initialized by non-static constructors.
  • Static constructors are implicitly called, whereas non-static constructors must be explicitly called.
  • Static constructors execute immediately once the execution of a class starts, and moreover, it's the first block of code to run under a class, whereas non-static constructors execute only after creating the instance of the class as well as each and every time the instance of the class is created.
  • In the life cycle of a class, the static constructor executes one and only one time, whereas the non-static constructor executes for '0' time if no instance of the class is created and for 'n' times if the 'n' times instance has been created.
  • Non-static constructors can be parameterized, but static constructors can't have any parameters because they are static constructors are impliedly called, and moreover, it's the very first block of the class to be executed, so how do I send the parameters?
  • Non-static constructors can be overloaded, whereas static constructors can't be overloaded.

Note: A static member of the class can be directly accessed in the static block.

Here's the code example in C#

using System;

class MyClass
{
    // Static field
    private static string staticMessage = "Hello, I am a static message.";

    // Static method accessing the static field
    public static void DisplayStaticMessage()
    {
        Console.WriteLine(staticMessage);
    }

    // Main method
    static void Main()
    {
        // Accessing the static field directly within the static block
        Console.WriteLine("Static message within the static block:");
        Console.WriteLine(staticMessage);

        // Calling a static method that accesses the static field
        Console.WriteLine("\nCalling a static method:");
        DisplayStaticMessage();
    }
}

Enter fullscreen mode Exit fullscreen mode

Every class contains an implicit constructor if it is not defined explicitly, and those implicit constructors are defined based on the following criteria:

  • Every class except a static class contains an implicit non-static constructor if not defined with an explicit constructor.
  • Static constructors are implicitly defined only if that class contains any static fields, or else that constructor will not be present at all.
💖 💪 🙅 🚩
mzunairtariq
M ZUNAIR TARIQ

Posted on January 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related