In this article we will learn creating a private contructor and instantiating an object.
Introduction
From the first time we started learning OOPs we have learnt about constructors that they are always publc with no return type self executable and same name as class name, but constructors can be private !! means we cannot instantiate any object of that class so wat is the use? suppose i know the name of the class and u have made a default public constructor there by i can create an object and can use the members of the class in order to prevent object creation i will made the constructor private. So the question is how to make an object.
We can create an object within the static method and then can create objects of the class , until and unless u dont know the method name we cant create objects of the class.
We create a static method with return type class which will return ur objectusing System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace privatecontructor
{
public class Class1
{
//private constructor
private Class1()
{
}
//create a static method with class return type, as it will return the object
public static Class1 clobj()
{
Class1 h = new Class1();
return h;
}
public void abc()
{
MessageBox.Show("hello");
}
}
}
Here we create a class type variable the keep the reference of the returned objectusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testprvconts
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// to store the object
privatecontructor.Class1 a;
a = privatecontructor.Class1.clobj();
a.abc();
}
}
}
It will print hello!!
Rest is self explanatory. If you have any queries u r welcome . i am new so spare if there is any mistakes
Thus we created a object with a private constructor..