---
title: "关于构造函数和继承的加载顺序问题"
author: "hellsing42"
date: "2007-09-26T10:35:44Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2007-09-26T10:35:44Z"
id: 127215
url: "https://hellsing42.iteye.com/blog/127215"
---

```

class   X   {   
  Y   b   =   new   Y();   
        X()   {     
  System.out.print("X");     
  }   
  }   
  class   Y   {   
          Y()   {     
  System.out.print("Y");     
  }   
  }     
  public   class   Z   extends   X   {   
              Y   y   =   new   Y();   
                Z()   {     
  System.out.print("Z");     
  }   
                public   static   void   main(String[]   args)   {   
                          new   Z();   
                }   
  }   

```

  为什么输出的是YXYZ啊？ 
根据结果的解释是:   
    new   Z（）时创建class   Z的对象，从变量的声明开始一步步执行了   new   Y（）   
  输出Y了；然后执行Z（）构造函数，由于Z是从X继承而来的，所以执行X（）   
  的构造函数，输出X，再进行变量的声明，输出Y了，最后构造Z（）输出Z