Can't Instantiate Field (instance variable) in main() method. Why?? Java

北城以北 提交于 2019-12-12 00:24:36

问题


Can someone tell me what I am doing wrong here? When I have this code in Eclipse, it is telling me I cannot "make a static reference to a non-static field" when I try to set sheetName to "hi" in the main method. What am I doing wrong here? I know it must be simple, but I searched everywhere and cannot figure it out!

public class AutoExpire {

private String sheetName;
private FileInputStream inputStream;

/**
 * Instantiates the class.
 */
public AutoExpire() {
    // do nothing
}

/**
 * The main method from which the program is ran.
 * 
 * @param args
 *            No arguments.
 * @throws IOException
 *             If program fails to run.
 */
public static void main(String[] args) throws IOException {

    sheetName = "hi";

回答1:


The main method is static, so you have no instances of AutoExpire in the main method. Create an instance, then set the instance's field.

public static void main(String[] args) throws IOException {
    AutoExpire ae = new AutoExpire();
    ae.sheetName = "hi";


来源:https://stackoverflow.com/questions/17181243/cant-instantiate-field-instance-variable-in-main-method-why-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!