我创建了一个静态字段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");
}
}
最佳答案
您不能在方法内声明 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");
}
}
关于java - 创建静态字段时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589534/