繁体   English   中英

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

[英]Java: Why can't I declare the reference-variable in one statement and create the referenced object in another statement of the class?

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

我不明白为什么第一个版本是不可能的。 我还尝试了一个 int 值(它不是一个对象 - 我认为):

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

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

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

File file1 = new File("path");

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

您可以使用块语句来做到这一点:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM