package Ejercicios;
public class Swan {
private String name = "Fluffy";
{
System.out.println("setting field");
}
public Swan() {
name = "Tiny";
System.out.println("setting constructor");
}
static {
System.out.println("Static initalization.");
}
public static void main(String[] args) {
Swan chick = new Swan();
Swan chick2 = new Swan();
}
}
Departure
Static initalization.
setting field
setting constructor
setting field
setting constructor
I'm trying to understand these initialization blocks, but I don't understand this part of the static
Why does the Static initalization only print once?
Because the static block will only be executed when the class
Swap
is loaded into memory (every Java class generates an instance of type Class ) and for that reason it prints firstStatic initalization.
In this case it gave this result because the class
Swap
was the main class (where the method ismain
). But what if the static block is not in the classSwap
, but inSwap2
? Well, the block would not be executed first.Example:
Result on screen:
In this case, after assigning the base address of the object to the variable
chick
, the classSwap2
will be loaded into memory and then the static block is executed.Even if we create more than one instance of type
Swap2
, the static block will only execute once when the class is loaded into memory.Static is a class attribute, not an instance attribute, therefore it is only used once per class, this would be the brief explanation, it has more crumb behind it if you want to know about it. We would say that "Static" makes any attribute global for the whole class and therefore it is only seen once printed even if you have instantiated it twice.
the static in this case is unique for the entire class (occupies a single place in memory). If you won't use static, the system creates a new place for that variable or constant or method with each instance (the variable is different for each object).