// That doesn't work:
import java.io.File;
public class Test {
File file1;
file1 = new File("path");
}
//--------------------------------------
// The following works:
import java.io.File;
public class Test {
File file1 = new File("path");
}
I don't understand why the first version is not possible. I also tried it with an int-value (which is not an object - I think):
//Also doesn't work:
public class Test {
int number;
number = 4;
}
Thank you! I tried it and it works (without implementing a non-default constructor or a method):
import java.io.File;
public class Test {
int number;
{
number = 4;
}
File file1;
{
file1 = new File("path");
}
public static void main(String[] args) {
Test test = new Test();
System.out.print(test.number + " , " + test.file1.getName());
// Output: 4 , path
}
}
You can do it with a block statement :