Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface question.........

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:

What will be the output when class Test is run ?
Options :1) It will print 1
2)It will print ii=2, j=3, jj=4 and then 1
3)It will print ii=2 and then 1
4)It will not compile
5)None of the above..
Answer: 1)It will print 1.
I cannot understand how does the output only prints 1 without printing the value of ii
??
Please explain..
Sonir
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sonir,
very interesting thing happens here i guess.
try to print J.jj or I.ii. it prints the message in the out() method.
but again, its little strange. 'coz it also prints message for var 'j' in J interface when we just print J.jj!!
So, i guessed that all the vars initialized with const are compile time loaded and rest who depends upon some class thing gets loaded first time when ANY of the var is loaded (when we try to access it first time).
this loading is only ONCE as the vars are final. so, if u try to print J.jj again it just prints value of J.jj without calling out() method again.

here is the code i used,

the output was,
1
j 3
jj 4
4
4

any other pointers?
regards
maulin.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup Maulin, you are on the right track.
The expression J.i is a compile time constant. That is, the compiler can completely evaluate the value of J.i without having to load any classes/interfaces or run any code. That's because interface J inherits the i member from interface i, and the member i is a public, static, and final variable with a value 1. Since this value can never change while the program is running, the compiler is able to create code for the println() statement that just sticks the value "1" in-line, without having to look at the J interface at run time.

Rob
 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys..
I am still not clear with the concept..
Why does J.jj prints 2 sets of different answers??

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic