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

another K&B mock question

 
gianni ipez
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I can't understand the result of the following code:



The result o f the run is :
r1 r4 pre b1 b2 r3 r2 aigle

I don't understand why the static code in class Rapace is executed before the instantiation of Aigle Object.
This means that all the static code inside a project is executed during compilation?
Or there's something related to inheritance between Oiseau/Rapace/Aigle objects since Aigle is inside the main method?

Thanks for clarifying my shameful confusion !

Gianni
 
Rachil Chandran
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static code is executed (once) when the class is loaded into the JVM
 
gianni ipez
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rachil.
And when does a class is loaded in JVM?
Do all the classes of a project are loaded in JVM before the execution of main method?
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not positive, but i BELIEVE that each class is loaded just before it is needed for the first time. you may have a branch in your code that never needs certain classes, so (again, i think) those will never be loaded.
 
gianni ipez
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in fact if I add a class that has nothing to do with the others, the static code is not executed :


"reptile" is not printed out.

So maybe the jvm is so intelligent to know, before invoking main method, all the classes that will be directly involved in the execution...
is that right?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No the code is executed when the JVM needs the class and will then load that class into memory. Your reptile class is never used and will so never loaded into memory.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Fred Rosenberger:
I am not positive, but i BELIEVE that each class is loaded just before it is needed for the first time...

Exactly. Any of the following can cause a class to load (if not already loaded):
  • Accessing a static member
  • Creating a new instance
  • Calling Class.forName("ClassName")
  •  
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic