Java:为什么我不能在一个语句中声明引用变量并在类的另一个语句中创建引用的对象?


// 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");
}

我不明白为什么第一个版本是不可能的。 我也尝试使用整数值(这不是一个对象 - 我认为(:

//Also doesn't work:
public class Test {
int number;
number = 4;
} 

谢谢!我试过了,它可以工作(没有实现非默认构造函数或方法(:

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
}
}

这是因为在方法之外的类定义中不能有可执行代码。所以这条线

file1 = new File("path");

(这是一个声明(,是非法的。它永远不会被执行。类定义在编译时处理,但编译器不是虚拟机,它不执行代码。语句在运行时执行。

正如 B.M 所指出的,您可以创建一个静态代码段,该代码在加载类时执行。但是,我相信它相当于你的第二个例子:

File file1 = new File("path");

(但我承认没有为此检查字节码(。

你可以用一个块语句来做到这一点:

public class Test {
File file1 ;
{
file1 = new File("path");
}
}

最新更新