• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Interface Doubt

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interface I
{
int i = 1;
int ii = Test.out("ii", 2);
}
interface J extends I
{
int j = Test.out("j", 3), jj = Test.out("jj", 4);
}
interface K extends J
{
int k = Test.out("k", 5);
}
class Test {
public static void main(String[] args)
{
System.out.println(J.i);
System.out.println(K.j);
}
static int out(String s, int i)
{
System.out.println(s + "=" + i);
return i;
}
}

produces the output:

1
j=3
jj=4
3

My expected O/p is

1
j=3
3


But how "jj=4" also gets printed?
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Classes, interfaces are loaded in their first active use.

For the first statement:
System.out.println(J.i);
'i' is a variable in interface 'I' that is a compile time constant, refering to that field doesnt cause the interface and its fields to be initialized.

System.out.println(K.j);
'j' is a variable in interface 'J' thats is not a compile time constant, refering to that field causes the interface and its fields to be initialized, but not those in its super interface nor in its sub interface.

Even interface 'K' is used to access those fields in its super interfaces, it doesnt cause it to be initialized.
 
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in the first interface i=1 i.e public static final i = 1, so it becomes compile time constant, so the other fields in the interface are not called but in the class J ,the value of j depends on the function, so it is not a compile time constant and hence all the fields in that interface is run and hence we get the output
 
She'll be back. I'm just gonna wait here. With this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic