JAVA构造函数运行解析

发表于:2007-07-04来源:作者:点击数: 标签:
源代码如下 import java .util.*; class super1{ { System.out.println(super1 ok); } super1() { System.out.println(3); } } class Employee extends super1{ private String name; private double salary=1500.00; private Date birthday; public Employee
源代码如下
import java.util.*;
class super1{
{
System.out.println("super1 ok");
}
super1()
{
System.out.println("3");
}
}

class Employee extends super1{
private String name;
private double salary=1500.00;
private Date birthday;
public Employee(String n,Date DoB){
System.out.println("2");
name=n;
birthday=DoB;
}
public Employee(String n){
this(n,null);
System.out.println("4");
}
}

class Manager extends Employee{
{
System.out.println("Manager ok");
}
private String department;
public Manager(String n,String d){
super(n);
department=d;
}
}

public class test1{
public static void main(String args[]){
new Manager("Smith","sales");
}
}

new Manager("Smith","sales")调用过程:
(1)绑定构造函数参数。其实就是传递参数的过程
(2)查看是否有this()语句。没有。虽然没有使用this()语句调用构造函数,但是该步骤不能省略
(3)调用super()语句,此时,程序跳转到Public Employee(String n)。
(4)绑定构造函数参数String n
(5)查看是否有this()。有,则执行构造函数public Employee(String n,Date DoB)
(6)绑定构造函数参数String n,Date DoB
(7)查看是否有this()语句。没有
(8)执行有系统自动插入的super()语句:执行super1()
(9)执行显式初始化语句System.out.println("super1 ok");
(10)执行构造函数语句System.out.println("3");
(11)执行显式初始化语句private double salary=1500.00;
(12)执行构造函数语句System.out.println("2");同时执行name=n;birthday=DoB;
(13)执行构造函数语句System.out.println("4");
(14)执行显式初始化语句System.out.println("Manager ok");
(15)执行构造函数语句department=d;

几点总结:
(1)对象是由new运算符创建的,且在任何构造函数执行之前就已经创建完毕了
(2)构造函数的执行总是“向上”的:而且总是先执行完父类的构造函数
(3)在构造函数中,没有this()语句则由super()语句。没有this()时,或者自己编写super(),或者由系统自动调
用 super()
(4)显式初始化语句总是先于构造函数语句,但后于super()或this()


原文转自:http://www.ltesting.net