What is the difference between CONSTRUCTOR and INITIALIZER? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference between CONSTRUCTOR and INITIALIZER?

5th Jan 2017, 8:49 AM
Nochains
Nochains - avatar
2 Answers
+ 3
Instance initializers are a useful alternative to instance variable initializers whenever: initializer code must catch exceptions, or perform fancy calculations that can't be expressed with an instance variable initializer. You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. Instance initializers are also useful in anonymous inner classes, which can't declare any constructors at all.
5th Jan 2017, 10:47 AM
Alex
Alex - avatar
+ 1
A constructor will "build" an instance when it is call. And the initializer will be call on the load of the class. You can have two type of initializer. but it's will be better with code: public class A { static int staticVariable; int instanceVariable; // Static block: static { System.out.println("Static"); staticVariable = 5; } // Instance block: { System.out.println("Instance"); instanceVariable = 10; } // Constructor public A() { System.out.println("Constructor"); } public static void main(String[] args) { new A(); new A(); } } and the output will be: Static Instance Constructor Instance Constructor As we can see the static is load only one at the begining (normal it's static, call only of the first call of the class). After the instance and finally the constructor.
5th Jan 2017, 10:48 AM
Florian Castelain
Florian Castelain - avatar