-
March 21st, 2011, 03:44 AM
#1
Can we create object of class with private constructor?
Hi,
Can we create an object of a class having private constructor. If so, then how? Please tell me.
Thanks in advance
-
March 21st, 2011, 11:45 AM
#2
Re: Can we create object of class with private constructor?
I would think that if the constructor is private, then no non-member could access the constructor. However, class members including static members would still be able to do so.
so one might build a class such as the following...
Code:
public partial class xyz {
public string abc;
public int number;
private xyz() {
abc = "this is a public string";
number = 7;
}
public static xyz pleaseConstructAnObjectForMe() {
return new xyz();
}// end function 'pleaseConstructAnObjectForMe'
}// end this segment, class 'xyz' partial declaration
and call it as follows ...
Code:
// xyz pXYZ = new xyz(); // doesn't compile!
xyz pXYZ = xyz.pleaseConstructAnObjectForMe();
MessageBox.Show(pXYZ.abc);
indeed, I may be mistaken, but I seem to recall seeing instances in the .NET Framework where classes couldn't be constructed other than by referencing a static function.
OldFool
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|