aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interface Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Interface Doubt" Watch "Interface Doubt" New topic
Author

Interface Doubt

vatsalya rao
Ranch Hand

Joined: Feb 14, 2007
Posts: 63
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

Joined: Apr 22, 2006
Posts: 424
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

Joined: Oct 09, 2007
Posts: 206

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


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interface Doubt