Topic: 一道csjp题目

  Print this page

1.一道csjp题目 Copy to clipboard
Posted by: gutxgc
Posted on: 2006-05-13 11:57

class Phone {
2. static String device = "Phone.device";
3. void showDevice() {
4. System.out.print("Phone.showDevice," + device + " ");
5. }
6. Phone() {
7. showDevice();
8. }
9. }

1. class Mobile extends Phone {
2. String device = "Mobile.device";
3. void showDevice() {
4. System.out.print("Mobile.showDevice," + device + " ");
5. }
6. Mobile() {
7. showDevice();
8. }
9. public static void main(String[] args) {
10. Mobile n = new Mobile();
11. n.showDevice();
12. }
13. }

CHOICES:
1 Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device

2 Phone.showDevice,Phone.device Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device

3 Mobile.showDevice,null Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device

4 Compile Time error

5 RunTimeException is thrown

The correct answer is 3. Can anyone explain why?

2.Re:一道csjp题目 [Re: gutxgc] Copy to clipboard
Posted by: tomcatexpert
Posted on: 2006-05-14 03:38

这是一道很有趣的题目.

Constructor的执行顺序是
1. Call this() or super (),一层层叫上去,直到Object为止
2. 执行所有member attributes 的赋值.
3. 执行Constructor 内部的Code

所以,本题中当Mobile被建立时,顺序是这样的
1. Phone ()
2. String device = "Mobile.device"; // Mobile 类
3. Mobile() 里面的代码

具体结果就是:
1. Phone()被呼叫时,Mobile 类的device还没被赋值,而Phone() 里的showDevice() 被Overriden,所以打印结果是 Mobile.showDevice,null
2. Mobile类的device被赋值
3. 此时再执行Mobile() 里的showDevice(),效果和在main() 方法使用n.showDevice()一样,各打印一个Mobile.showDevice,Mobile.device

推荐阅读:Thinking in Java

3.Re:一道csjp题目 [Re: gutxgc] Copy to clipboard
Posted by: gutxgc
Posted on: 2006-05-14 11:12

大谢谢了
等了好久才有回
没有弄明白构造函数的调用顺序
所以总以为调用super()时不会输出null

4.Re:一道csjp题目 [Re: gutxgc] Copy to clipboard
Posted by: hong_sea
Posted on: 2006-05-16 16:49

JAVA中的构造函数的执行顺序:

1 初始化一个空间,并且赋值为空或者NULL;
2 执行父类的构造函数;
3 执行本身的属性的初始化;
4 执行本身的构造函数。

所以上面的对买的执行情况:
1 Mobile初始化空间,赋值为NULL;
2 执行Phone的构造函数,Phone(),函数体中包括一个showDevice() 方法,但是此方法已经被重写,所以执行的是Mobile中的showDevice() ,但是此时还没有到给本身属性初始化值的时候,所以属性值为null,输出“Mobile.showDevice,null”。
3 给本地属性初始化值,初始化 String device = "Mobile.device"。
4 执行本身的构造函数,此构造函数包括一个showDevice() 方法,但是此时已经给device初始化数值了,所以输出“Mobile.showDevice,Mobile.device ”。
5 执行本地showDevice() 方法,输出“Mobile.showDevice,Mobile.device ”。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923