• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the meaning of "Interface Initialization Does Not Initialize Superinterfaces"?

 
nemo zou
Ranch Hand
Posts: 35
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found thiis topic in webpage
and this code:


the output is


Why there is a jj=4 in the output? Is it because j and jj are both static variables in interface J?
 
Ashley Bye
Ranch Hand
Posts: 132
2
Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the comments below that output on the website explain what is going on quite well, although it does need a bit of thought to get your head around what is happening:

The reference to J.i is to a field that is a constant variable (§4.12.4); therefore, it does not cause I to be initialized (§13.4.9).
The reference to K.j is a reference to a field actually declared in interface J that is not a constant variable; this causes initialization of the fields of interface J, but not those of its superinterface I, nor those of interface K.
Despite the fact that the name K is used to refer to field j of interface J, interface K is not initialized.


If you look at the main() method, the first line prints out the value of i, which is 1. Since i is ssigned a constant, no further initialisation is taken on the interface.
The second line is a bit more interesting in that both variables j and jj need to be computed before a value is assigned to them. So j gets computed first, and the result of this computation is printed by the out() method of Test, giving j=3. But because the variable j needed initialisation, all other variables in the J interface are initialised. So jj is computed too, which is why jj=4 is printed. So now we have Interface J with two variables, j=3 and jj=4. The execution of line 2 continues and prints out the calculated value for j, 3. Hence we get the output as shown.

The reason that the variables are referenced through a sub-interface is to demonstrate that a super-interface will not be initialised unless one of it's variables needing computation is explicitly requested. It also demonstrates that to initialise k, K.k would need to have been accessed directly.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nemo zou wrote:Why there is a jj=4 in the output? Is it because j and jj are both static variables in interface J?

The same code snippet is discussed in this thread as well. Have a look and see if you can answer the bonus question too
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic