File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confuse in static block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confuse in static block" Watch "Confuse in static block" New topic

Confuse in static block

srinibash udayasingh

Joined: Jul 09, 2007
Posts: 22
Hi Ranchers
i am confuse in following code

class A
class B
class C extends B
class D
public static void main(String[] args)
C c=new C();

out put is B C
can anyone explain it..

Jaideep Kshirsagar

Joined: Aug 29, 2007
Posts: 27
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

Joined: Sep 26, 2006
Posts: 22
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.

Praveen Kumar S.<br />SCJP 1.4<br />Score : 90%
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
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"

Thanks and Regards
Bob Ruth
Ranch Hand

Joined: Jun 04, 2007
Posts: 320
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 ]

SCJP - 86% - June 11, 2009
I agree. Here's the link:
subject: Confuse in static block
It's not a secret anymore!