Explain the output of java code containing interfaces

I had come across a question for which I am not able to find out why its output is coming as

7

when I calculate mathematically it can produce output as 7, 8 or any other number So my question is on what basis its coming as 7 only

interface InterfaceA
{
    int A = InterfaceB.B * 2;
}

interface InterfaceB
{
    int B = InterfaceC.C + 1;
}

interface InterfaceC extends InterfaceA
{
    int C = A + 1;
}

public class TestInterface implements InterfaceA, InterfaceB, InterfaceC {
    public static void main(String[] args) {
        System.out.println(A + B + C);
    }
}
Jon Skeet
people
quotationmark

Obviously code like this should never actually occur. It's horrendous. I don't think you should spend too much time worrying about why it gives 7, but it's actually not too hard to see why.

The first field value to be evaluated is InterfaceA.A, so the VM starts to initialize InterfaceA. That requires InterfaceB.B, so it starts to initialize InterfaceB. That requires InterfaceC.C, so it starts to initialize InterfaceC.

Now although InterfaceC.C refers to InterfaceA.A, the VM is already initializing InterfaceA, so it just proceeds regardless (as per section 12.4.2 of the JLS):

If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.

So InterfaceA.A is still 0 (we're still trying to work out what value it should have, and 0 is the default value for int), and InterfaceC.C gets a value of 1 (0 + 1). Then InterfaceB.B gets a value of 2 (1 + 1), and InterfaceA.A gets a value of 4 (2 * 2).

Sum all of those field values, and you end up with 7.

If you use a different expression, you'll get a different value because you'll see a different interface being initialized last, although it only depends on the first field which you refer to:

A + B + C = 7 (A = 4, B = 2, C = 1)
A + C + B = 7 (A = 4, B = 2, C = 1)
B + A + C = 3 (A = 0, B = 2, C = 1)
B + C + A = 3 (A = 0, B = 2, C = 1)
C + A + B = 6 (A = 2, B = 1, C = 3)
C + B + A = 6 (A = 2, B = 1, C = 3)

(You have to replace the existing line of code of course, as this is about type initialization - if you just add more System.out.println lines you'll get the same answer for all the above expressions.)

people

See more on this question at Stackoverflow