A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

构造方法的执行:在类中方法外出现;多个构造方法方法中相同的代码存放到一起,每个构造方法执行前,都首先执行构造代码块.
这句话不是特别理解,构造方法不是对对象的属性初始化么,这个意思如何理解?!

3 个回复

倒序浏览
4.类的初始化过程:
                加载class文件
                堆中开辟空间
                变量的默认初始化
                变量的显示初始化
                构造代码块初始化
                构造方法初始化
          成员变量-->构造代码块-->构造方法
  1. class Student
  2. {
  3.         String name;
  4.         static int i;
  5.         //构造代码块
  6.         {
  7.                 System.out.println("Student的构造代码块2......");
  8.         }
  9.         {
  10.                 System.out.println("Student的构造代码块1......");
  11.         }

  12.         //构造方法
  13.         Student(){
  14.                 System.out.println("Student的无参构造方法!");
  15.         }

  16.         //静态代码块
  17.         static{
  18.                 System.out.println("静态代码块2...... i = " + i++);
  19.         }
  20.         static{
  21.                 System.out.println("静态代码块1...... i = " + i);
  22.         }
  23.        

  24.        
  25. }
  26. class Demo
  27. {
  28.         public static void main(String[] args)
  29.         {
  30.                 Student stu1 = new Student();
  31.                 Student stu2 = new Student();
  32.                 Student stu3 = new Student();
  33.         }

  34.        
  35. }
复制代码
回复 使用道具 举报 1 0
您需要登录后才可以回帖 登录 | 加入黑马