Sneha
Sneha

Reputation: 488

Why objects of the static class cannot be created? and which constructor a static class contains?

As i searched and got few points static class is sealed and uses private constructor internally then why in my code i am not able to access the method using the class name using System?

using System; 

public sealed class ClasswithPrivateCons { 
  private ClasswithPrivateCons() { } 
  public void Printname() { Console.WriteLine("Hello world"); }
}
public class Program { 
  public static void Main() { 
    ClasswithPrivateCons.Printname(); // gives error
  }
} 

Upvotes: 1

Views: 330

Answers (2)

Ihor Konovalenko
Ihor Konovalenko

Reputation: 1407

  1. Sealed class is not static. When a class is defined as a sealed class, this just means that class cannot be inherited. You must create instance of it before use. Sealed class with private constructor doesn't automatically become a static class. Static class has behaviour like sealed, but it represents separate kind of object in OOP. "Sealed" just means that class cannot be inherited, but in any case we must create an instance. At the same time, static class can't be instantiated.
  2. Constructor of class must be public, otherwise we could not create instance. Instance constructor not only initialize new object, it also responsible for creating new objects and getting them ready to use. Constructor, unlike ordinary method, leverages inner .NET mechanisms aimed to create new instance.
    public sealed class ClasswithPrivateCons
    {
        public ClasswithPrivateCons() { }
        public void Printname() { Console.WriteLine("Hello world"); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClasswithPrivateCons cl = new ClasswithPrivateCons();
            cl.Printname();
        }
    }

Also Printname method can be declared as static. Than it may be called

ClasswithPrivateCons.Printname();

Upvotes: 1

AKX
AKX

Reputation: 169398

It would be useful if you also included the error you're getting, but in this case it's obvious: Printname is not a static method, so you can't call it without an instance of ClasswithPrivateCons(). Since that constructor is private, you can't construct those objects.

Three resolution options:

  • Make Printname() static; then ClasswithPrivateCons.Printname() will work
  • Make the constructor public; then new ClasswithNoLongerPrivateCons().Printname() will work
  • Add a public static factory method that calls the private constructor:
    • public static ClasswithPrivateCons New() { return new ClassWithPrivateCons(); }
    • ClassWithPrivateCons.New().Printname()

Upvotes: 3

Related Questions