I have a simple Java program as follows:
public class HelloWorldPrinter {
String filepath;
public void setPath(String path){
this.filepath = path;
}
public static void main(String[] args) throws PrintException, IOException {
FileInputStream in = new FileInputStream(new File(filepath));
}
}
I am getting the following error:
HelloWorldPrinter.java:40: error: non-static variable filepath cannot be referenced from a static context
FileInputStream in = new FileInputStream(new File(filepath));
How can I fix this?
One option is to create an instance of HelloWorldPrinter
:
public static void main(String[] args) throws PrintException, IOException {
HelloWorldPrinter printer = new HelloWorldPrinter();
printer.setPath("path/to/file");
FileInputStream in = new FileInputStream(new File(printer.getPath()));
}
you can never access non static field inside static field.
because static field does not need object, and non-static does , so static field will never know the state of non-static field.
so you have two option rather make your field static
, or create an object before accessing it
.
HelloWorldPrinter obj= new HelloWorldPrinter();
FileInputStream in = new FileInputStream(new File(obj.getPath()));
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.