Hi,
A class cannot be instantiated when it has Private constructor. Abstract class also serve the same purpose. Then, What is the difference between abstract class and a class with private constructor?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jaish MathewsPosted May 16, 2010, 4:57 AM
1st of all keep your analysis and thinking attitude. The world is the proof that inventions and innovations are always coming from the part of the world where government or society not blocking the free thoughts and questioning mentality of it's people.
Now the answer is that , difference residing in it's usage. You already mentioned one similarity, but we are using them in different ways like below
Usage of Private Constructor
Private constructor class is using to create a specific creation pattern named "Singleton". This pattern enables to create only a single object of the class shares among various client applications. In real time, LoadBalancing applications using for sharing work load among different machines should be imlemented with singleton. Because all servers should access the same instance to update it. Below is a simple example which imlemented Singleton uisng private constructor
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
and need to create instance like below
Singleton s = Singleton.Instance;
One more point that a class with private constructor can't inherit. Try to inherit the below class.
public class MyPrivate
{
private MyPrivate()
{
}
}
It will display compile error.
Error 1 'ConsoleApplication1.MyPrivate.MyPrivate()' is inaccessible due to its protection level D:\PERSONAL\ConsoleApplication1\Program.cs 27 16 ConsoleApplication1
But Abstract class itself meant for using only through inheritance.
One more hidden point is that, once you inherited a class from Abstract class, your abstract class constructor is executing automatically. You may not aware of this. But run below code and see that your abstract class constructor is execting.
class Program : MyAbstract
{
static void Main(string[] args)
{
//When ever this line is executing, the below mentioned abstract class constructor will be executed.
Program p = new Program();
}
}
public abstract class MyAbstract
{
//This will be executed automatically.
public MyAbstract()
{
}
}
Pooja SharmaPosted May 19, 2010, 12:03 AM