创建静态字段时出错

时间:2014-12-21 12:53:51

标签: java static

我在班级上创建了一个静态字段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");
    }
}

2 个答案:

答案 0 :(得分:2)

您无法在方法内声明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");
    }
}

答案 1 :(得分:1)

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

将其移到外面:

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");
    }
}
相关问题