Hello All, This question is taken from JQ+. There were two question using the same code and asking the same question " What will be the output when class Test is run ? " but the only difference was in the main method. One question had the print statement marked as //1 and the other question had the print statement marked as //2 .
The answer to the above 2 questions are as follows
Que 1) It will print 1 ( System.out.println(J.i) in the main method) Que 2) it wil print j = 3, jj=4 and then 3 ( System.out.println(K.j) in the main method)
And these are my answers which are wrong
Ans to Que 1 ) It will print ii=2, j = 3, jj=4 and then 1 ( System.out.println(J.i) in the main method)
Ans to Que 2) It will print j=3, jj=4, k=5 and then 3 ( System.out.println(K.j) in the main method)
Interface is loaded when a constant is accessed or assigned to a variable.
For Que 1, since i is defined in Interface K and J extends K, it inherits the variable i. So when J.i is accessed, its super interface will be loaded first and initialized and since all the constants are static and final, they will be initialized in the order they appear. The same loading and initialization will happen for Interface J after Interface K is loaded and Initialized.
For Que 2, I applied the same steps described for Que 1.
My answers were based on the above described understanding which obviously is wrong.
Could some one kindly explain it step by step in detail. My exam is on the 22nd and would really appreciate an early response.
Hope the problem described is clear and not confusing. Thanks in advance. Kind Regards. Hasnain Javed Khan.
Originally posted by-Varalakshmi Why is this printing j=3 jj=4 //--> Why is this line getting printed? 3
I was expecting it to print just j=3 3
Hi, Here as you are calling System.out.println(K.j); // 1 and you can see that J is not a compile time constant. So the super interface will be loaded and initialized , this leads to intializing of super interface of K. thus j and jj of Interface J gets intialized. This puts a call to TestInterface.out() method on both, there by giving j=3,jj=4 also. But this is not the case with System.out.println(J.i); as i is a compile time constant.So for this we just got output for i=1.