Non-static instance initialization and static instance Initialization
Java also has a similar syntax called instance initialization, which is used to initialize non-static variables of 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 following instance initialization clause:
{
Mug1 = new Mug (1 );
Mug2 = new Mug (2 );
System. out. println ("mug1 & mug2 initialized ");
}
It seems like a static initialization clause, except that the static keyword is missing. This syntax is required for initialization that supports "anonymous internal classes, however, it also allows you to ensure that some operations will happen no matter which display constructor is called. The output shows that the instance initialization clause is executed before the two constructors.