jiten
jiten

Reputation: 5264

difference between sealed class and sealed class with private constructor

Is there any difference in

public sealed class A
{

} 

public sealed class B
{
     private B()
     {}
} 

So what is the reason to use private constructor in sealed class

Upvotes: 2

Views: 1072

Answers (1)

Jamiec
Jamiec

Reputation: 136154

The two things are tangential, which is to say that one is unrelated from the other.

  • Sealed classes cannot be inherited
  • Classes with private constructors cannot be intantiated publically.

So what is the reason to use private constructor in sealed class

Quite possibly the implementation of a Singleton. There is no point inheriting it (so its sealed) and you dont want devs instantiating new instances (you want them to use the Singleton instance)

Upvotes: 5

Related Questions