zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    在mac上如何用safari浏览器调试ios手机的移动端页面
    VSCode 入门
    Redux和Context对比
    七种CSS左侧固定,右侧自适应两栏布局
    componentWillMount VS componentDidMount
    react-native IOS TextInput长按提示显示为中文(select | selectall -> 选择 | 全选)
    MySQL调优5---查询优化
    MySQL调优4---索引
    MySQL官网下载案例数据库
    MySQL调优3---执行计划
  • 原文地址:https://www.cnblogs.com/smile0120/p/5465923.html
Copyright © 2011-2022 走看看