Constructors

What is constructor with example

Constructors are special methods inside a class that is called when an object is instantiated. In other words, when we create an instance of the class using the “new” keyword, the constructor gets called automatically and initializing the variables of that class.

Example:

Suppose we have a “Car” class as mentioned below

class Car
{
    private string _name;
    private string _type;
}

Now if we want to initialize “Car” class variables whenever someone creates an instance of a class. The constructor can easily solve this problem please refer below code snippet.

class Car
{
    private string _name;
    private string _type;

    public Car(string name, string type)
    {
        _name = name;
        _type = type;
    }
}

Now whenever we create an object of class “Car” we need to pass the name and type to create an instance

Car car = new Car("5 Series (E39)", " SEDAN");

When we create an instance of “Car” class, the Constructor of the “Car” class is called and initializes name and type with provided values i.e. “5 Series (E39)” and “SEDAN” respectively.

Online Free Constructor Quiz

Constructor Definition

A constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables

Point to remember

  • A default constructor is called automatically if no constructor is declared in the class
  • The constructor name is the same as that of the class name.
  • The constructor does not have any return type.
  • Constructor called whenever an object of a class is created.
constructor meaning, constructor definition, object oriented programming constructor, types of constructor in java, constructors c++, constructor javascript, constructor in c#, constructor in python, default constructor in java

In any object-oriented programming language, constructor represents the same concept i.e. special method used to initiate the class objects. So, Constructor java, constructor C#, constructor Python, or constructor C++ conceptual represent the same.

Read More about Object-Oriented Programming Concepts

https://corevoila.in/net/object-oriented-programming-tutorials/object-oriented-programming-opps/

Types of Constructors

Below are the list of different types of a Constructor.

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor
  • Private Constructor

Default constructor

The default constructor does not have parameters, so while creating an instance of a class we don’t need to provide the parameters. Every class has constructor But sometimes we don’t need to declare explicitly (in .Net, framework create a default constructor in C# if not created explicitly, a similar way in Java default constructor will be created by JVM if not created explicitly).

When we have some code to be executed while creating instance without parameter that time, we need to explicitly declare the default constructor. Default constructors are always public.

In the below example we have defined a class without defining explicit default constructor in the class, but still, we are able to create an instance of this class with the help of the “new” keyword.

class DemoClass 
{
    public int ii=100;
    public string _type = "BASE";

}

Client to access the above class

class ClientDemoClass
{
    public void Print()
    {
        DemoClass demoClass = new DemoClass();
        Console.WriteLine(demoClass.ii);
    }

}

In the above example, we do not give any value to the variables within the class and we also do not have any explicit constructor defined in the class, so DemoClass variables will be initialized with the default values.

Default Constructor or Parameter less Constructor Example:

In the below program we will explicitly create constructor

 System;

namespace Demo
{
    class DemoClass
    {
        public DemoClass()
        {
            Console.WriteLine("Default Constructor!");
        }
    }

    class ClientDemoClass
    {
        static void Main()
        {
            Console.WriteLine("Let's Instance of DemoClass");
            DemoClass p = new DemoClass();
            Console.WriteLine("Completed creating Instance of DemoClass");
            Console.ReadLine();
        }
    }
}

The output of this program will be as given below:

Let’s Instance of DemoClass
Default Constructor!
Completed creating Instance of DemoClass

When the program runs, it prints prints “Let’s Instance of DemoClass”. Then it goes to create an instance of the class using the new keyword. So, the constructor is called, and the line written inside the constructor gets executed “Default Constructor!”. After creating the instance from Main() method it prints “Completed creating Instance of DemoClass”.

Parameterized constructor

When there is a need to initiate a member of a class whenever someone creates an instance of the class, we use a Parameterized constructor.

For Example:

namespace Demo
{
    class Car
    {
        private string _name;
        private string _type;

        public Car(string name, string type)
        {
            _name = name;
            _type = type;
        }
    }

    class ClientCar
    {
        static void Main()
        {
            Car car = new Car("Audi","Sedan");
        }
    }

}

In the above program, we have created a Parameterized constructor for the class “Car”. So, After creating a constructor now to create an instance of a car we need to pass the parameters. If we do not pass the parameters, we will get the compile-time error.

In case we don’t need to pass the parameter then we can add a default constructor to the above class.
So that we can create a class instance without passing the parameters as we can see in below code snippet

namespace Demo
{
    class Car
    {
        private string _name;
        private string _type;

        public Car(string name, string type)
        {
            _name = name;
            _type = type;
        }

 public Car()
        {
            _name = “Car”;
            _type = “Default Type”;
        }

    }

    class ClientCar
    {
        static void Main()
        {
            Car car = new Car("Audi","Sedan");
     Car car1 = new Car();
        }
    }

}

With the above example, we see that we can create two instances of class one with passing parameter (Parameterized Constructor) and another one without passing parameter (Default Constructor)

Note: Multiple Constructor can be created in a class, with different parameter as it supports overloading. overloading, which states that more than one method, with the same name but different signatures, can be defined within the same class, and depending upon the signature of the method, the appropriate method gets called. Notice that we have defined parameterized constructors and default constructor in this class.

Copy constructor

Copy constructors are used when we need to initialize a class instance by existing class instance value. suppose we want to create an instance of the class using the existing instance of the same class. Copy constructor takes the instance of that same class as a parameter and initializes the member variables for the instance of the class being created.

For example

namespace Demo
{
    class Car
    {
        private string _name;
        private string _type;

        public Car(string name, string type)
        {
            _name = name;
            _type = type;
        }

        public Car(Car c)
        {
            _name = c._name;
            _type = c._type;
        }
    }

    class ClientCar
    {
        static void Main()
        {
            Car car = new Car("Audi", "Sedan");
            Car car1 = new Car(car);

        }
    }
}

In the above example, we have created an object of “car” class and now we are creating another instance of car class with the help of the existing instance.

Why we need copy constructor?

There may be situations where many values need to be passed for instantiating the class. Moreover, we need to instantiate such class objects more than once with the same values. So instead of passing the same values again to create new instances of such a class, we can create copy constructors to create such instances.

Static constructor

A Static constructor is responsible for initializing the static variables and to perform a particular action that needs to be performed only once. static constructors are always called implicitly before the first instance is created or any static members are referenced from a class. There is no explicit information when it gets called automatically for the runtime (read more about beforefieldinit).

Note: static constructor should not have access modifiers or parameters.

For example

using System;

namespace Demo
{
    class Car
    {
        private string _name;
        private string _type;

        static Car()
        {
            Console.WriteLine("Static Constructor!");
        }

        public Car(string name, string type)
        {
            _name = name;
            _type = type;
        }

        public Car(Car c)
        {
            _name = c._name;
            _type = c._type;
        }
    }

    class ClientCar
    {
        static void Main()
        {
            Car car = new Car("Audi", "Sedan");
            Car car1 = new Car(car);
            Console.ReadLine();
        }
    }
}

In the above example, we see that we did not call the static constructor but still it will get called by the compiler automatically.

Private Constructor

A Private Constructor is used in singleton class, where singleton class ensures that no more than one object can be created at a time. private constructor prevents to create an instance of a class. To access the instance of private constructor class we need static members.

using System;

namespace Demo
{
    class Car
    {
        public static int CarCount;

        public static int IncrementCount()
        {
            return ++CarCount;
        }
        private Car()
        {

        }
    }

    class ClientCar
    {
        static void Main()
        {
            
            Console.WriteLine(Car.IncrementCount());
            Console.ReadLine();
        }
    }
}

In the above example, we created a private constructor so we will not be able to create an instance of a class using a “new” keyword, but we can access static members of a class.

Constructor Resources


Leave a Reply

Your email address will not be published. Required fields are marked *