簡體   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