Monday, January 17, 2011

Private Constructor

Private Constructor
You can also use make your constructor private. If constructor is private so it restricts the object to instantiate using new keyword. You can’t create object of private constructor but you can use access static members of class by calling them from class name. Private constructors are used when you don’t want to create an object of class or you don’t want the class to be inherited.


Example



In this program we have create a private constructor and variable Name as static. First we will look that what happen if we instantiate an object of private constructor.




Can't instantiate an object of private constructor. You can see that it says that you can't access the object Human() because of its protection level.


Now without instantiating object we will use static variable.






We have to call static variable with class name as we have done here Human.Name.






Now we will make another class and will inherit the Human class to see that the class contain private constructor can be inherit or not.




It gives the same error when we were creating object of private constructor.


Read about Constructor, Constructor Overloading, Constructor Chaining

No comments:

Post a Comment