wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confuse in static block" Watch "Confuse in static block" New topic
Author

Confuse in static block

srinibash udayasingh
Greenhorn

Joined: Jul 09, 2007
Posts: 22
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

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
Greenhorn

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 ]

------------------------
Bob
SCJP - 86% - June 11, 2009
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confuse in static block
 
Similar Threads
parameterpassing
String Comparison.
a question about exception
this #2
how to create a boolean truth table