I was reading about initializers in Java.
I read almost all the Stackoverflows related questions, and I became quite familiar with what a constructor is ,and, what non-static (instance) initilizer blocks and static initializers are.
I think I did understand they're order of execution, and how they differ.
Anyway, there is something that concern me. This is the fact that a static field can be initialized by constructors and by instance initializer blocks.
I did read that doing that is considered bad practice, isn't it?
So now, I'm asking myself why this action\feature is allowed by the compiler?
Why it doesn't give any error?
Maybe, It's useful to a certain degree or in a certain way.....
Code Example:
public class Potato {
static int x;
{x=10;}
public tuna(int a) {
System.out.println(x);
x=a;
}
}
public class MainClass {
public static void main (String[] args) {
Potato tom = new Potato (6);
System.out.println(tom.x);
Potato nick = new Potato (7);
System.out.println(tom.x);
}
}
Ouput:
10
6
10
7