java菜鸟基础问题

来源:百度知道 编辑:UC知道 时间:2024/05/25 06:36:55
public class Test2{
public static int aMethod() {
static int i = 0;
i++;
return i;
}
public static void main(String[] args) {
Test2 test = new Test2();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}//不是说静态变量用静态方法吗,怎么第三行还有错

静态变量i应该在aMethod()前先声明,改为
public class Test2{
static int i = 0;
public static int aMethod() {
i++;
return i;
}
public static void main(String[] args) {
Test2 test = new Test2();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
就可以了

在静态方法内声明的变量都是静态变量。
public class Test2{
public static int aMethod() {
static int i = 0; i++; //
return i;
}
//报错是因为这行等同于 static static int i=0须去掉static
应该写成
public class Test2{
public static int aMethod() {
int i = 0;
i++;
return i;
}

是这样的。

哎,java的语法规则规定了不允许在方法中申明静态变量。
仅此而已,不要被上面那些代码搞懵了。

//报错是因为这行等同于 static static int i=0须去掉static

这个完全是牵强附会嘛,呵呵。
你难道说java编译器在编译这些代码的时候会先编译成static static,再编译成字节码??

这仅仅是Java的语法规则。

更何况,按这个意识,那么非静态的方法里面就可以这样申明啦?
很显然同样是不可以的。

总之,规则是,方法里面是不能申明静态变量的,不能什么。

其实我们是可以想