简体   繁体   中英

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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