• java 初始化块


    1. class Bike8{  
    2.     int speed;  
    3.       
    4.     Bike8(){System.out.println("constructor is invoked");}  
    5.    
    6.     {System.out.println("instance initializer block invoked");}  
    7.        
    8.     public static void main(String args[]){  
    9.     Bike8 b1=new Bike8();  
    10.     Bike8 b2=new Bike8();  
    11.     }      

    In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the constructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the figure given below:

    instance initializer block

    Rules for instance initializer block :

    There are mainly three rules for the instance initializer block. They are as follows:
    1. The instance initializer block is created when instance of the class is created.
    2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
    3. The instance initializer block comes in the order in which they appear.

    class A {
    A() {
    System.out.println("parent class constructor invoked");
    }
    }

    class Test extends A {
    Test() {
    super();
    System.out.println("child class constructor invoked");
    }

    {
    System.out.println("instance initializer block is invoked");
    }

    public static void main(String args[]) {
    Test b = new Test();
    }
    }

    输出:

    parent class constructor invoked
    instance initializer block is invoked
    child class constructor invoked

    class A {
    A() {
    System.out.println("parent class constructor invoked");
    }
    }

    class Test extends A {
    Test() {
    super();
    System.out.println("child class constructor invoked");
    }

    Test(int a) {
    super();
    System.out.println("child class constructor invoked " + a);
    }

    {
    System.out.println("instance initializer block is invoked");
    }

    public static void main(String args[]) {
    Test b1 = new Test();
    Test b2 = new Test(10);
    }
    }

    输出:

    parent class constructor invoked
    instance initializer block is invoked
    child class constructor invoked
    parent class constructor invoked
    instance initializer block is invoked
    child class constructor invoked 10

  • 相关阅读:
    Linux 头文件详解
    Linux 进程运行状态
    配置uboot指定nfs挂载根文件系统
    (实例)Linux 内核添加exfat驱动
    Linux 内核 编译模块
    简单添加自己的驱动程序到Linux内核树中
    Linux 生成随机mac地址,并固化到本地
    (转)为什么ssh一关闭,程序就不再运行了?
    Ubuntu 安装 QtCreator (version : Qt 5.9.8)
    Ubuntu 固定自己的IP
  • 原文地址:https://www.cnblogs.com/smile0120/p/5465923.html
Copyright © 2020-2023  润新知