public class Main { public int SvrPrt = 0; public static void main(String[] args) { // TODO 自动生成方法存根 SvrPrt = 10; System.out.println(SvrPrt);; } }偶是新手,这个小程序在“SvrPrt = 10;”编译错误,显示是“不能对非静态字段 SvrPrt 进行静态引用”,请问这是为什么?
public int SvrPrt = 0;这样子定义 public static int SvrPrt=0;在main里就可以引用了,这是因为类的静态方法不能访问类的非静态成员造成的,
public class Main { public int SvrPrt = 0; public static void main(String[] args) { // TODO 自动生成方法存根 SvrPrt = 10; System.out.println(SvrPrt);;//这里的两个分号是干什么的? } }
如果要在static方法中访问非static的成员,需要new当前类的对象来访问Main m = new Main(); m.SvrPrt = ...... ...
public int SvrPrt = 0; public static void main(String[] args) {
// TODO 自动生成方法存根
SvrPrt = 10;
System.out.println(SvrPrt);;//这里的两个分号是干什么的?
}
}
m.SvrPrt = ......
...
除非将某个object 引用传入static方法,然后通过该引用.便可以调用non-static了