Java – obfuscate initialization of instance variables

I was taking the scjp test and did some simulation tests. I met this one:

It asks what is the output of:

class TestClass
{
   int i = getInt();
   int k = 20;
   public int getInt() {  return k+1;  }
   public static void main(String[] args)
   {
      TestClass t = new TestClass();
      System.out.println(t.i+"  "+t.k);
   }
}

I think this will be 21.20 because T.I will call getInt and then increase K to 21.20

But the answer is 1.20 I don't understand why it's 1. Can anyone see that?

Solution

Variables are initialized from top to bottom

What's going on?

>Initially, both K and I have a (default) value of 0. > The value calculated by getint() (then 0 1) is assigned to I > 20 and to k > 1 20 for printing

Good reading:

> The Java ™ Tutorials: Initializing Fields

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>