【问题标题】:Error when creating a static field [duplicate]创建静态字段时出错[重复]
【发布时间】:2015-02-19 18:37:11
【问题描述】:

我在课堂上创建了一个静态字段 c,但它生成了一个错误,提示 illegal start of expression

请帮我解决这个问题。

public static void main(String[] args) {

    System.out.println("program started.");    
    static Controller c; //Where the error is

    try {
        Model m = new Model();
        View v = new View();
        c = new Controller(m,v);
        c.sendDataToView();
        c.showView();
    } catch(Exception ex) {
        System.out.println("error");
    }
}

【问题讨论】:

    标签: java static


    【解决方案1】:

    您不能在方法内声明 static 字段(或任何其他字段),即使它是 static 字段。

    您可以在方法外声明static 字段:

    static Controller c;
    public static void main(String[] args) {
        System.out.println("program started.");
    
        try {
           Model m = new Model();
           View v = new View();
           c = new Controller(m,v);
           c.sendDataToView();
           c.showView();
        }catch(Exception ex) {
            System.out.println("error");
        }
    }
    

    或者一个普通的老式局部变量:

    public static void main(String[] args) {
        System.out.println("program started.");
    
        Controller c;
        try {
           Model m = new Model();
           View v = new View();
           c = new Controller(m,v);
           c.sendDataToView();
           c.showView();
        }catch(Exception ex) {
            System.out.println("error");
        }
    }
    

    【讨论】:

    • 你能解释一下为什么不允许在方法中声明一个字段吗?
    • @Francisco 这不是 java 的工作方式 - 字段是 class 的成员,因此它们应该在类下声明 - 方法内的变量是该方法的本地变量,因此不需要(也不能拥有)访问修饰符,final 除外。
    【解决方案2】:

    您不能在方法中声明静态字段。

    把它移到外面:

    static Controller c;
    
    public static void main(String[] args) 
    {
        System.out.println("program started.");
        try {
            Model m = new Model();
            View v = new View();
            c = new Controller(m,v);
            c.sendDataToView();
            c.showView();
        } catch(Exception ex) {
            System.out.println("error");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多