Deep Understanding of Private Constructor


Introduction

Hi all . before starting this article i wanted to say that this article is deep understanding of "Private Access Modifier"  and the students Those who really wanted to dig into this topic,this article is for you.

Get Started

This article is specific to private modifier. We will discuss the advantages of using "Private Access Modifier",How to declare this  and why we need this even though there is other access modifiers are available.

Lets dig into this topic........


Is Private Keyword Possible in Class?

This is very Interesting question. Some may say Yes Some may say No. Lets see In action .

Fig 1

See the Fig 1 . I am getting compile time error when i tried to declare Private keyword. 

Now there is a question comes to our mind... How can we implement private to a class.

Lets see in action.


Fig 2
In fig-2 I defined a private constructor which makes the class private. So when i tried to create an object of testclass in Program class , then compile time error will show "Inaccessible due to protection level".

Benefits

  • Basically Private class is used in singleton design pattern.
  • When I wanted to restrict my class members to access outside the class then we should go for Private class.
  • When i wanted to restrict a class to create an object.


Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts