一道有趣的Java面试题

第一种情况:

 1 public class B {
2
3 public int n = 10;
4
5 public B(){
6 System.out.println("out:B");
7 draw();
8 }
9
10 public void draw() {
11 System.out.println("out:B---"+n);
12 }
13 }
 1 public class A extends B {
2
3 public int n = 10;
4
5 public void draw() {
6 System.out.println("out:A---"+n);
7 }
8
9 public A(int n){
10 this.n = n;
11 System.out.println("out:A");
12 }
13 public static void main(String[] args) {
14 A a = new A(5);
15 }
16 }

得出的结果:

out:B
out:A---0
out:A

第二种情况(B类不变):

 1 public class A extends B {
2
3 public static int n = 10;
4
5 public void draw() {
6 System.out.println("out:A---"+n);
7 }
8
9 public A(int n){
10 this.n = n;
11 System.out.println("out:A");
12 }
13 public static void main(String[] args) {
14 A a = new A(5);
15 }
16 }

得到的结果:

out:B
out:A---10
out:A

第三种情况:

 1 public class B {
2
3 public int n = 10;
4
5 public B(){
6 System.out.println("out:B");
7 draw(n);
8 }
9
10 public void draw(int n) {
11 System.out.println("out:B---"+n);
12 }
13 }
 1 public class A extends B {
2
3 public int n = 10;
4
5 public void draw(int n) {
6 System.out.println("out:A---"+n);
7 }
8
9 public A(int n){
10 this.n = n;
11 System.out.println("out:A");
12 }
13 public static void main(String[] args) {
14 A a = new A(5);
15 }
16 }

得到的结果:

out:B
out:A---10
out:A

这个与java类的加载顺序有关,有兴趣的朋友可以去看看:

http://blog.csdn.net/zlb824/article/details/6948441

转载于:https://www.cnblogs.com/loveJava/archive/2011/11/08/2241261.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值