1

can someone please explain me, why var is not allowed here, outside the main method? If i were to remove var and make these declarations the "normal" way, this does not happen.

public class Test {

var test = new Test();
var integer = 10;


public void doActionA(){
    System.out.println("Hello");
}

public static void main(String[] args){
    
    for(int i = 1; i <100; ++i){
        new Thread(() ->{
            var test2 = new Test();
            var integer2 = 20;




        }).start();
    }
}

}

Haoshoku
  • 27
  • 1
  • 5
  • The same reason you can't do that without `var`, I believe. – erip Jul 22 '20 at 22:15
  • The first duplicate tells you where `var` can be used. The second duplicate should address your question of "why", assuming you were looking for reasons why `var` is not allowed in field declarations outside of "because that's what the spec says". – Slaw Jul 22 '20 at 22:23
  • Doesn't the fist create a stackOverflowException by continually creating new Test objects? – NomadMaker Jul 22 '20 at 22:36

0 Answers0