Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confuse in static block

 
srinibash udayasingh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers
i am confuse in following code

class A
{
static{System.out.println("A");}
};
class B
{
static{System.out.println("B");}
};
class C extends B
{
static{System.out.println("C");}
};
class D
{
public static void main(String[] args)
{
C c=new C();
}
}

out put is B C
can anyone explain it..

Regards
Srinibash
 
Jaideep Kshirsagar
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you write 'new C()' the object for class C is created and while creation of this object as C extends from B, inherently static block in B gets executed and then static block in C.
 
Praveen Kumar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi srini,
The answer is very simple.
According to inheritence, first it will execute all the static blocks and constructors of parent class gets executed first and then the child class.

All the best.
 
Satya Maheshwari
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not think this has something to do with constructors.When you instantiate a class, it has to be loaded first. While its being loaded, its static initializer block executes. Here you are instantiating object of class C. So it has to be loaded, and its base class is to be loaded as well to ensure that sub class object inherits from base class. Hence you see the output as "B C"
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static initializers execute when the object is loaded (before it is ever instantiated!)

instance initializers execute each time the class instantiates, in the constructor, after the (implied or explicit) call to super() and the first line of your class' constructor logic.

And, if there are multiples of either, they all execute at the same time (for the type.... static or instance) from top to bottom in the class definition.
[ August 30, 2007: Message edited by: Bob Ruth ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic