Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface Doubt

 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • 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?
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • 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.
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic