简体   繁体   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");
}

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):我还尝试了一个 int 值(它不是一个对象 - 我认为):

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

It's because you cannot have executable code in the class definition outside a method.这是因为您不能在方法之外的类定义中包含可执行代码。 So the line所以线

file1 = new File("path");

(which is a statement), is illegal. (这是一个声明),是非法的。 It never gets executed.它永远不会被执行。 The class definition is processed at compile time, but the compiler is not a virtual machine, it doesn't execute your code.类定义在编译时处理,但编译器不是虚拟机,它不会执行您的代码。 Statements are executed at runtime.语句在运行时执行。

You can, as BM noted, create a static piece of code which is executed when the class is loaded.正如 BM 所指出的,您可以创建一段静态代码,在加载类时执行该代码。 But, I believe it is equivalent to your second example:但是,我相信它相当于你的第二个例子:

File file1 = new File("path");

(but I admit not to have checked the bytecode for that). (但我承认没有为此检查字节码)。

You can do it with a block statement :您可以使用块语句来做到这一点:

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

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

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