Java also has a similar syntax called instance initialization, which is used to initialize non-static variables for each object. For example:
: Initialization/mugs.java
Java "Instance initialization."
Class Mug {
Mug (int marker) {
System.out.println ("Mug (" + marker + ")");
}
void f (int marker) {
System.out.println ("f (" + marker + ")");
}
}
public class Mugs {
Mug Mug1;
Mug Mug2;
{
MUG1 = new Mug (1);
MUG2 = new Mug (2);
System.out.println ("Mug1 & Mug2 initialized");
}
Mugs () {
System.out.println ("Mugs ()");
}
Mugs (int i) {
System.out.println ("Mugs (int)");
}
Publis static void Main (string[] args) {
SYSTEM.OUT.PRINTLN ("Inside Main ()");
New Mugs ();
System.out.println ("New Mugs () completed");
New Mugs (1);
System.out.println ("New Mugs (1) completed");
}
}/* Output:
Mug (1)
Mug (2)
MUG1 & MUG2 Initialized
Mugs ()
New Mugs () completed
Mug (1)
Mug (2)
MUG1 & MUG2 Initialized
Mugs (int)
New Mugs (1) completed
*///:~
The instance initialization clause in this:
{
MUG1 = new Mug (1);
MUG2 = new Mug (2);
System.out.println ("Mug1 & Mug2 initialized");
}
It appears to be exactly the same as a static initialization clause, except the static keyword, which is necessary to support the initialization of an anonymous inner class, but it also allows you to guarantee that whatever display constructor is called, some operations will occur. You can see from the output that the instance initialization clause was executed before the two constructors.
Non-static instance initialization