A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class.
Example :
class Geek
{
.......
// Constructor
public Geek() {}
.......
}
// an object is created of Geek class,
// So above constructor is called
Geek obj = new Geek();
Important points to Remember About Constructors
- Constructor of a class must have the same name as the class name in which it resides.
- A constructor can not be abstract, final, and Synchronized.
- Within a class, you can create only one static constructor.
- A constructor doesn’t have any return type, not even void.
- A static constructor cannot be a parameterized constructor.
- A class can have any number of constructors.
- Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
Types of Constructor
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Private Constructor
- Static Constructor
Default Constructor
A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.
Example :
C#
using System;
namespace DefaultConstructorExample {
class Geek {
int num;
string name;
Geek()
{
Console.WriteLine( "Constructor Called" );
}
public static void Main()
{
Geek geek1 = new Geek();
Console.WriteLine(geek1.name);
Console.WriteLine(geek1.num);
}
}
}
|
Output :
Constructor Called
0
Note : This will also show some warnings as follows:
prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and will always have its default value `0'
prog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Geek.name' is never assigned to, and will always have its default value `null'
Parameterized Constructor
A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.
Example :
C#
using System;
namespace ParameterizedConstructorExample {
class Geek {
String name;
int id;
Geek(String name, int id)
{
this .name = name;
this .id = id;
}
public static void Main()
{
Geek geek1 = new Geek( "GFG" , 1);
Console.WriteLine( "GeekName = " + geek1.name +
" and GeekId = " + geek1.id);
}
}
}
|
Output :
GeekName = GFG and GeekId = 1
Copy Constructor
This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance.
Example :
C#
using System;
namespace copyConstructorExample {
class Geeks {
private string month;
private int year;
public Geeks(Geeks s)
{
month = s.month;
year = s.year;
}
public Geeks( string month, int year)
{
this .month = month;
this .year = year;
}
public string Details
{
get
{
return "Month: " + month.ToString() +
"\nYear: " + year.ToString();
}
}
public static void Main()
{
Geeks g1 = new Geeks( "June" , 2018);
Geeks g2 = new Geeks(g1);
Console.WriteLine(g2.Details);
}
}
}
|
Output :
Month: June
Year: 2018
Private Constructor
If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class.
Points To Remember :
- It is the implementation of a singleton class pattern.
- use private constructor when we have only static members.
- Using private constructor, prevents the creation of the instances of that class.
Example :
C#
using System;
namespace privateConstructorExample {
public class Geeks {
private Geeks()
{
}
public static int count_geeks;
public static int geeks_Count()
{
return ++count_geeks;
}
public static void Main()
{
Geeks.count_geeks = 99;
Geeks.geeks_Count();
Console.WriteLine(Geeks.count_geeks);
Geeks.geeks_Count();
Console.WriteLine(Geeks.count_geeks);
}
}
}
|
Output :
100
101
Static Constructor
Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once.
Points To Remember :
- It can’t be called directly.
- When it is executing then the user has no control.
- It does not take access modifiers or any parameters.
- It is called automatically to initialize the class before the first instance created.
Example :
C#
using System;
namespace staticConstructorExample {
class geeks {
static geeks()
{
Console.WriteLine( "Static Constructor" );
}
public geeks( int i)
{
Console.WriteLine( "Instance Constructor " + i);
}
public string geeks_detail( string name, int id)
{
return "Name:" + name + " id:" + id;
}
public static void Main()
{
geeks obj = new geeks(1);
Console.WriteLine(obj.geeks_detail( "GFG" , 1));
geeks obj1 = new geeks(2);
Console.WriteLine(obj1.geeks_detail( "GeeksforGeeks" , 2));
}
}
}
|
Output :
Static Constructor
Instance Constructor 1
Name:GFG id:1
Instance Constructor 2
Name:GeeksforGeeks id:2
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Nov, 2020
Like Article
Save Article