zoukankan      html  css  js  c++  java
  • JAVA & .NET创建对象构造函数调用顺序

    JAVA

    定义Person类

    package models;
    ​
    public class Person {
        public Person() {
            System.out.println("person constructor");
        }
    ​
        {
            System.out.println("person init block");
        }
    ​
        static {
            System.out.println("person static block");
        }
    }

    定义Chinese类

    package models;
    ​
    public class Chinese extends Person {
        public Chinese() {
    //        super();
            System.out.println("chinese constructor");
        }
    ​
        {
            System.out.println("chinese init block");
        }
    ​
        {
            System.out.println("chinese init block2");
        }
    ​
        static {
            System.out.println("chinese static block");
        }
    ​
        static {
            System.out.println("chinese static block 2");
        }
    }

    创建Chinese类实例

    public class Program {
        public static void main(String[] args) {
            new Chinese();
        }
    }

    输出结果如下:

    person static block
    chinese static block
    chinese static block 2
    person init block
    person constructor
    chinese init block
    chinese init block2
    chinese constructor

    执行顺序为:

    基类静态初始化块——当前类静态初始化块——基类初始化块——基类构造函数——当前类初始化块——当前类构造函数

    ⚠️ JAVA中加载类时会调用类的静态代码块

    try {
        Class.forName("models.Chinese");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    执行结果如下:

    person static block
    chinese static block
    chinese static block 2

    .NET

    与JAVA相比,.NET中没有初始化块及静态初始化块

    定义类型如下:

    class Person
    {
        public Person()
        {
            Console.WriteLine("person constructor");
        }
    ​
        static Person()
        {
            Console.WriteLine("person static constructor");
        }
    }
    ​
    class Chinese : Person
    {
        public Chinese()
        {
            Console.WriteLine("chinese constructor");
        }
    ​
        static Chinese()
        {
            Console.WriteLine("chinese static constructor");
        }
    }

    创建对象:

    class Program
    {
        static void Main(string[] args)
        {
            new Chinese();
        }
    }

    输出结果如下:

    chinese static constructor
    person static constructor
    person constructor
    chinese constructor

    执行顺序为:

    当前类静态构造函数——基类静态构造函数——基类构造函数——当前类构造函数

    小结

    JAVA与.NET创建对象时都是先执行静态代码块后执行非静态代码块;

    JAVA先执行基类中的静态及非静态代码块;

    .NET先执行当前类中的静态代码块,然后先执行基类中的实例构造函数;

  • 相关阅读:
    32 最小子串覆盖
    31 数组划分
    29 交叉字符串
    动态规划
    18 带重复元素的子集
    17 子集
    16 带重复元素的排列
    23.二叉树的后续遍历序列
    J.U.C-其他组件
    21.Longest Palindromic Substring(最长回文子串)
  • 原文地址:https://www.cnblogs.com/Cwj-XFH/p/10425739.html
Copyright © 2011-2022 走看看