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

What is difference between the instanck block and constructor?

30th Sep 2019, 1:15 PM
Thriveni Sunkara
Thriveni Sunkara - avatar
2 Answers
+ 1
Both will be execute when you create an object. At first the instance block and then the constructor. A constructor can get values. For example: public myClass(int num){ this.num = num; } In an instance block you could do this: { num = 7; } But without an constructor it is not possible to create an object with a specific value. You would need to write a setter for int num and to call this method. //with constructor MyClass my = new MyClass(4); //without constructor MyClass my = new MyClass(); my.setNum(4); Here is a code about static and instance block: https://code.sololearn.com/cRKxAwr2rE6t/?ref=app
30th Sep 2019, 1:42 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Specify the language in Relevant Tags please.
30th Sep 2019, 3:36 PM
Ipang