Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

???? Outer and Inner Class ????  RSS feed

 
AmitVijay AVKulkarni
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

Please go through the following code. Also I am giving output of the code.
I need to find out how this is happening?

class Outer3 extends OuterTest
{
static
{
System.out.println("static block");
}

Inner3 i = new Inner3();

public Outer3()
{
System.out.println("Outer1 constructor");
}

class Inner3
{
public Inner3()
{
System.out.println("Inner1 constructor");
}
}


}

public class OuterTest
{
public OuterTest()
{
System.out.println("OuterTest constructor");
}

public OuterTest(int pInt)
{
System.out.println("OuterTest constructor pInt : "+pInt);
}
public static void main(String args[])
{
Outer3 o = new Outer3();
}
};

When I compile and run this code the output I get is

static block
OuterTest constructor
Inner1 constructor
Outer1 constructor

regards,
Amit
 
yash Vi
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the following might answer your question

Order Of Execution of static Initialiser Block:-

1.static block of class that contains main method
2.The main method starts execution.
Note :- static bolck of other classes are executed only if the class is instantiated
atleastonce.
3.when executing the static block of the instantiated class, if it has a super class the
static block of the super class is first instantiated and
then the static bolck of this class.

4.If a class has more than one static blocks, its all combined and considered as one.
5 static block is executed only once i.e during the first instance.


6.A static variable is initialised in the first instance and the value retained in the following ones.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!