中意人寿的IT笔试题目之阅读程序

来源:互联网 发布:北京新华电脑软件学校 编辑:程序博客网 时间:2024/04/27 16:43

public class X {

Y b = new Y("X");

X(){

System.out.println(" X ");

}

 

}

 

public class Y {

Y(String n){

System.out.println(" Y in "+n);

}

 

}

 

public class Z extends X {

Y y = new Y("Z");

Z(){

System.out.println(" Z ");

}

 

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

 

new Z();

}

 

}

问输出结果:
 Y in X
 X 
 Y in Z
 Z 
原因分析:
Z是X的子类,所以在构建Z的时候先构建X。
于是构建X的时候,新建Y类然运行X的构造函数。
构建Z类,新建Y类然后运行Z构造函数。
TIPs:实例化类的时候,类中的其他类的实例也要实例化,并根据代码位置为先后顺序实例化。
public class MyThread extends Thread {
public void run(){
System.out.println("MyThread run()");
}
public void start(){
System.out.println("MyThread start()");
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("MyRunnable run()");
}
public void start(){
System.out.println("MyRunnable start()");
}
}
public static void main(String[] args) {
Thread myThread = new MyThread();
Runnable myRunnable = new MyRunnable();
Thread rThread = new Thread(myRunnable);
myThread.start();
rThread.start();
}
问输出结果:
MyThread start()
MyRunnable run()
分析原因:
Thread 在用start()启动的时候不会调用到run()函数。
用runnable创建的Thread用start()直接调用runnable的run()而不用调用start()函数。
马上补充一个Thread和runnable的比较文档。。。just wait a second!!

原创粉丝点击