• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static initializer...

 
Damodar Mukherjee
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code produce the output
b1 r1 r4 pre hawk and if I do noe extend Raptor to A then output is nothing!!! Why??? We know when a class forms the Static part will initialize but if we donot extend Raptor then also we should get the output...

Can any one please explain this...




 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you are not extending Raptor then why in the world will the static block be executed
 
Damodar Mukherjee
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So why it is executing when A is extending it???
And why not if other class in the same .java file extending some other class???
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class is initialized before a static method it declares is invoked, and all of its superclasses are initialized if they are not already initialized.
 
Paras Jain
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean to say you are not able to see even "pre" and "hawk" printed when you don't extend from Raptor?
 
Pankaj Patel
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Static block is executed only when a class is loaded in JVM.

Now if you are not extending Those classes then, those classes will not be loaded into JVM. And if those classes are not loaded in JVM, then obviouslly static block is not going to be executed. And that is what happening when you extends and dont extend Raptro Class.

Note : A class is loaded into JVM only once when you first create instance of it. After that if you make second instance of that class, static block of that class won't be executed becos that class already exist in JVM.


I hope i am making my self Clear.



======================================
Enjoy(ing) The World of Programming...
======================================
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class is loaded into JVM only once when you first create instance of it.

Also, when you refer to any static fields/methods of the class, or when you load it via reflection.
 
gianni ipez
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I posted a similar problem some days ago,
here you are:
http://www.coderanch.com/t/261887/java-programmer-SCJP/certification/another-mock

Hope it helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic