如下代码,输出结果是什么? public class Test { public int aMethod() { static int i = 0; i++; return i; } public static void main (String args[]) { Test test = new Test(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } }
时间: 2024-01-13 14:05:38 浏览: 27
这段代码是有语法错误的,因为在方法 aMethod() 中定义了一个静态变量 i,但是静态变量不能在方法中定义,只能在类中定义。
如果将静态变量 i 定义在类中,则输出的结果是 2。因为第一次调用 aMethod() 方法时,i 的值从 0 变为 1,并将 1 返回;第二次调用 aMethod() 方法时,i 的值从 1 变为 2,并将 2 返回。最后输出的 j 的值是 2。以下是修正后的代码:
```
public class Test {
static int i = 0;
public int aMethod() {
i++;
return i;
}
public static void main (String args[]) {
Test test = new Test();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
```
相关问题
public class Test { public int aMethod() { static int i = 0; i++; return i; } public static void main (String args[]) { Test test = new Test(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } }
这段代码有语法错误,无法通过编译。静态变量不能在方法内部声明。正确的写法应该是将静态变量 i 声明在方法外部,如下所示:
```
public class Test {
static int i = 0;
public int aMethod() {
i++;
return i;
}
public static void main(String[] args) {
Test test = new Test();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
```
此时输出结果为 2,因为 i 的值在两次调用 aMethod 方法时分别增加了 1。
以下程序运行结果正确的是:【 】 class Base { public void method() { System.out.println("不带参Base"); } } public class Sub extends Base { public void method() { System.out.println("不带参Sub"); } public int method(int a) { System.out.println("带参Sub"); return 0; } public static void main(String[] args) { Sub test = new Sub(); test.method(); test.method(0); } }
以下程序运行结果是正确的:
输出结果为:
不带参Sub
带参Sub
解析:
Sub类继承了Base类,并重写了method方法。在Sub类中,定义了两个method方法,一个是不带参数的方法,一个是带参数的方法。在main方法中,创建了Sub类的对象test,并分别调用了不带参数和带参数的method方法。由于Sub类重写了method方法,因此调用不带参数的method方法时,会调用Sub类中的方法,输出"不带参Sub";调用带参数的method方法时,会调用Sub类中的带参数的方法,输出"带参Sub"。因此,程序运行结果是正确的。