1

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
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
  • 1
    Compiler errors don't exist to enforce best practices. – shmosel Jan 30 '18 at 18:22
  • It's bad practice and (with most compiler settings) gives a warning to reference a static field with an instance expression instead of a class name. So, instead of `tom.x` you should write `Potato.x`. That makes it clear that `x` doesn't belong to the instance, but to the class. – Ralf Kleberhoff Jan 30 '18 at 18:39
  • @RalfKleberhoff I wanted to show the the instance changed in a way that you may not expect. – Gabriele Scarlatti Jan 30 '18 at 18:42
  • It's an example of mutable global state, which is bad because it makes the code hard to reason about. You can think the value is something, and then some part of the program you don't know about can change it to something else. Not a recipe for hair-retention. – Andy Turner Jan 30 '18 at 18:53
  • @GabrieleScarlatti Yes, I understand your question, but still `x` is not part of any **instance**, it's part of the **class** (and it's a pity that the Java language allows expressions like your example `tom.x`). – Ralf Kleberhoff Jan 30 '18 at 18:55

1 Answers1

2

What is the point of initializing a static variable in non static block ? You can modify the static variable in non static block because the static variable is considered as Class variable and the non static blocks, methods and variables are considered to be instance ones. Personally i would do static method which i will call from the static block to initialize the static variable.