Wednesday, July 18, 2012

Private constructor, Static constructor, Static method

Private Constructor

A class that has a private constructor cannot be instantiated outside the class.

A class having a private constructor cannot be inherited, otherwise you would be able to override the base class private constructor and create objects.

Helper and utility classes generally have private constructors so that we call their methods without creating objects.


Static Constructor

Static constructor is used to initialize static fields of a class.

Static constructor cannot be overloaded.

One class can have only one static constructor that initializes all its static members.

Static constructor is always parameter-less.

Static constructor can access only static members of the class and NOT non-static members of the class.

Non static constructor can access only non-static members of the class and NOT static members of the class, so the need for a separate constructor for the static members called static constructor.

Static constructor is called sometime before the first object of the class is created to initialize all the static members of the class.

No access specifier like public, private or protected can be applied to the static constructor.


Static Method

Static methods cannot access non-static members of the class but only static members.

Static methods cannot be called on any object but directly on the class name.

No comments:

Post a Comment