Static constructors are used to initializing the static members of the class and implicitly called before the creation of the first instance of the class. Non-static constructors are used to initializing the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Constructors.
Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error. However, we can pass the parameters to the non-static constructors.
Overloading: Non-static constructors can be overloaded but not the static constructors. Overloading is done on the parameters criteria. So if you cannot pass the parameters to the Static constructors then we can’t overload it.
Cases in which the constructor will be implicit: Every class except the static class(which contains only static members) always contains an implicit constructor if the user is not defining any explicit constructor. If the class contains any static fields then the static constructors are defined implicitly.
Execution: Static constructor executes as soon as the execution of a class starts and it is the first block of code which runs under a class. But the non-static constructors executes only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.
Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.
Initialization of fields: Static constructors are used to initialize the static fields and non-static constructors are used to initialize the non-static fields.
Declaration: Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called as Instance Constructors as they need instance to get executed.
Calling: Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.
No comments:
Post a Comment