Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and default constructor

A non static class can have static as well as default constructor at the same time.

What is the difference between these two constructors? When shall I go for only static or static with default constructor?

like image 524
Ram Avatar asked May 17 '10 13:05

Ram


People also ask

Can we have default constructor in static class?

Yes we can create the constructor of static class. static class A {static a(){//} }A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

What is the difference between constructor and static constructor?

A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members.

Which constructor executes first static or default?

then the static constructor is run before your default constructor, but when it runs, it's using new Single() , so passing through your non-static constructor path. This causes to call the default constructor before the static constructor.

What is a static constructor in Java?

A static constructor is the piece of code used to initialize static data, which means that a particular task needs to be executed only once throughout the program. It is usually called automatically before any static members referenced or a first instance is generated.


2 Answers

Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables.

On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.

like image 89
Giorgi Avatar answered Sep 28 '22 00:09

Giorgi


A static constructor runs only once, no matter how many objects of that type are created. A default constructor will run for each instance created by that constructor.

like image 28
Stephen Cleary Avatar answered Sep 28 '22 01:09

Stephen Cleary