zoukankan      html  css  js  c++  java
  • Java父类与子类执行顺序

    定义父类:

     1 public class Father {
     2     public Father() {
     3         System.out.println("father init");
     4     }
     5     
     6     static {
     7         System.out.println("father static init");
     8     }
     9     
    10     public void eat() {
    11         System.out.println("fahter eat");
    12     }
    13 }

    定义子类:

     1 public class Son extends Father {
     2     public Son() {
     3         System.out.println("son init");        
     4     }
     5     
     6     static {
     7         System.out.println("son static init");
     8     }
     9     
    10     @Override
    11     public void eat() {
    12         System.out.println("son eat");
    13     }
    14 }

    验证执行顺序:

    1 public class orderTest {
    2     public static void main(String[] args) {
    3         Father son = new Son();
    4         son.eat();
    5     }
    6 }

    执行结果:

    father static init
    son static init
    father init
    son init
    son eat

    执行顺序为:

    1、父类的静态代码块

    2、子类静态代码块

    3、父类构造方法

    4、子类构造方法

    5、子类的实例方法

  • 相关阅读:
    既然选择了远方,就只顾风雨兼程!
    slots
    面向对象
    模块和作用域
    偏函数
    python中decorator
    返回函数
    filter, sort
    map/reduce
    开发步骤
  • 原文地址:https://www.cnblogs.com/asenyang/p/15441429.html
Copyright © 2011-2022 走看看