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先执行当前类中的静态代码块,然后先执行基类中的实例构造函数;

  • 相关阅读:
    SQL Server 2019安装及部署指南
    西门子1200PLC实用定位控制程序案例
    C#进行注册表项和键值操作
    上位机开发必备的一个实体类
    配置Internal Load balancer中VM的外网访问
    从中序后序遍历构造
    网络 | Linux ping任何ip均出现 Destination Host Unreachable 排查思路与方法
    Spring、Spring Framework、Spring Boot、Spring Cloud的区别
    Linux软件安装目录分类讲解
    APP嵌入H5时,软键盘处理(IOS)
  • 原文地址:https://www.cnblogs.com/Cwj-XFH/p/10425739.html
Copyright © 2011-2022 走看看