Variable might not have been initialized error

前端 未结 11 1603
孤城傲影
孤城傲影 2020-11-21 05:50

When i try to compile this:

public static Rand searchCount (int[] x) 
{
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l

        
11条回答
  •  悲哀的现实
    2020-11-21 06:13

    If they were declared as fields of the class then they would be really initialized with 0.

    You're a bit confused because if you write:

    class Clazz {
      int a;
      int b;
    
      Clazz () {
         super ();
         b = 0;
      }
    
      public void printA () {
         sout (a + b);
      }
    
      public static void main (String[] args) {
         new Clazz ().printA ();
      }
    }
    

    Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.

提交回复
热议问题