zoukankan      html  css  js  c++  java
  • Java知识积累——静态代码块,非静态代码块,构造器的执行顺序和次数

    看如下程序

     1 class A {
     2    static{
     3       System.out.println("A static");
     4    }   
     5 
     6    {
     7       System.out.println("A not static"); 
     8    }   
     9 
    10    public A(){
    11       System.out.println("A new");
    12    }
    13 }
    14 
    15 class B extends A{
    16    static{
    17       System.out.println("B static");
    18    }   
    19 
    20    {
    21       System.out.println("B not static"); 
    22    }  
    23 
    24    public B(){
    25       System.out.println("B new");
    26    }
    27 } 
    28 
    29 public class MainTest {
    30    public static void main(String[] args) {
    31       A ab= new B();
    32       ab= new B();
    33    }
    34 }

    输出如下:

    A static

    B static

    A not static

    A new

    B not static

    B new

    A not static

    A new

    B not static

    B new

    结论: 

    静态代码块只有类首次加载进内存时调用一次,只此一次。

    非静态代码块,每次创建对象时,会在构造函数之前被调用。

    构造函数,每次创建对象时,最后调用。

    创建子类对象时,先创建父类对象,再创建子类对象。

    PS: 我存在过,我遇见过,我失败过。 有些路,明明有坑却从没人放警示牌。有些事,明明是错的却没人去管。有些话,明明应该告诉后来人却没人去说。 既然没人做,那就我来吧。希望我曾经历过的挫折不再重现于后来人。希望传承能够不是只挂在嘴边。希望人模人样的“人”能够真正做人。
  • 相关阅读:
    查询linux服务器有哪些IP在连接
    GitLab的使用
    jenkins安装
    GitLab安装
    Git for Linux
    PV并发UV
    yum安装zabbix故障报错
    redis备份恢复
    python递归-三元表达式-列表生成式-字典生成式-匿名函数-部分内置函数-04
    python函数闭包-装饰器-03
  • 原文地址:https://www.cnblogs.com/FlameRen/p/2886703.html
Copyright © 2011-2022 走看看