• 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
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

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
 
Something must be done about this. Let's start by reading this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic