有以下源程序,分别在不同的包中,请写出程序运行结果: package dir1; public class A{ public int i=1; private int j=2; protected static int k=6; public A(int i, int j){ i=i; this.j=j; } public float f(int x,int y) { return x+y+j; } protected double g(int i){ return this.i+i; } public int h(int n) { k+=n; return k; } } package dir2; import dir1.A; class B extends A{ int i=3; public B(){ super(3,4); } public double g(int m){ return super.g(m)+i; } public float f(int x,int y) { return x+y; } } public class Test{ public static void main(String[] args) { A a = new A(5,6); B b1=new B(); System.out.println(b1.g(2)); System.out.println(b1.h(3)); a=b1; System.out.println(a.f(1, 2)); B b2=new B(); System.out.println(b2.h(3)); } }
时间: 2023-05-22 21:05:03 浏览: 102
程序运行结果为:
10.0
3
2.0
3
注释:
- 第1次输出为 b1.g(2),b1 是 B 的实例化对象,调用 g 方法,输出的是 2 * 1 + 3 = 5.0。
- 第2次输出为 b1.h(3),b1 是 B 的实例化对象,使用了 A 中的 h 方法,将 j 的值赋为 3,然后返回 k 的值,即 3。
- 第3次输出为 a.f(1, 2),a 是 A 类型的变量,但是其实际指向的是 B 的实例化对象 b1,调用 f 方法,输出的是 1 * 2 = 2.0。
- 第4次输出为 b2.h(3),b2 是 B 的实例化对象,使用了 A 中的 h 方法,将 k 的值赋为 3,然后返回 k 的值,即 3。
相关问题
析下面程序运行结果: package com.huade.java; public class Test1 { public static void main(String args[]){ int i; int a[]={11,22,33,44,55,66,77,88,99}; for (i=0; i <= a.length / 2; i++) System.out.print(a[i] + a[a.length - i - 1] + " "); System.out.println(); } }
A:该程序会输出数组a中每个元素和对应位置上的倒数第i个元素的值,并以空格隔开。具体输出结果为:11 99 22 88 33 77 44 66 55 。其中,数组a的长度为9,由于循环中的i从0开始,因此i <= a.length / 2等价于i < 5。循环结束的条件为i=5时,此时已经输出了4对元素,即11 99、22 88、33 77、44 66,最后再输出55。
package com.exam; public class java { int i=0,j=-1; switch(i){ case 0:j=1; case 2:j=2; } System.out.print(""j=""+j); }
这段代码有语法错误,无法通过编译。在Java中,switch语句必须放在方法里面,不能直接在类中编写。正确的写法应该是:
```
package com.exam;
public class Java {
public static void main(String[] args) {
int i=0,j=-1;
switch(i){
case 0:j=1;break;
case 2:j=2;break;
}
System.out.print("j="+j);
}
}
```
在switch语句中,每个case后面必须跟着一个break语句,否则程序会继续执行下去。此外,Java中的类名应该以大写字母开头,变量名应该以小写字母开头。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)