0
What is difference between the instanck block and constructor?
2 Antworten
+ 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
+ 1
Specify the language in Relevant Tags please.