具体来说,我正在尝试这段代码:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
Run Code Online (Sandbox Code Playgroud)
但它给出了错误
无法访问静态方法main中的非静态字段
所以我把声明改为clock:
static Clock clock = new Clock();
Run Code Online (Sandbox Code Playgroud)
它奏效了.在声明之前放置该关键字是什么意思?对于该对象可以做什么,它究竟会做什么和/或限制什么?
class Foo {
public Foo() { }
}
class Bar {
static Foo foo = new Foo(); // This is legal...
public static void main(String[] args) {
static int a = 0; // ... But why this is not?
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我们不能在静态函数内声明静态变量?