zoukankan      html  css  js  c++  java
  • 子类继承父类时方法的调用顺序

    为了搞清当一个子类继承父类并调用了子类的某个方法时,在父类和子类中各个代码块的执行顺序

    我们自己创建一个父类Parent和一个子类Child,代码如下:

    父类代码

     1 package ParentAndChild;
     2 
     3 public class Parent {
     4     static{
     5         System.out.println("父类静态代码块");
     6     }
     7     
     8     {
     9         System.out.println("父类普通代码块");
    10     }
    11 
    12     public Parent() {
    13         super();
    14         System.out.println("父类构造器方法");
    15     }
    16     
    17     public void A(){
    18         System.out.println("父类A方法");
    19     }
    20     
    21 }

    子类代码:

    package ParentAndChild;
    
    public class Child extends Parent{
        static{
            System.out.println("子类静态代码块");
        }
        
        {
            System.out.println("子类普通代码块");
        }
        
        public Child() {
            super();
            System.out.println("子类构造器方法");
        }
    
        public void A(){
            System.out.println("子类A方法");
        }
        
        public static void main(String[] args){
            Child child =new Child();
            child.A();
        }
    }

    输出结果:

    结论:当一个子类继承父类并调用了子类的某个方法时代码块的执行顺序为 

                                        1)父类静态代码块
                                        2)子类静态代码块
                                        3)父类普通代码块
                                        4)父类构造器方法
                                        5)子类普通代码块
                                        6)子类构造器方法
                                        7)子类A方法

    也就是说遵循的原则如下:

      1.静态(变量)对象优先于非静态(变量)对象

      2.父类优先于子类

      3.按照成员表明量定义顺序进行初始化

        

  • 相关阅读:
    Day3----《Pattern Recognition and Machine Learning》Christopher M. Bishop
    Day2----《Pattern Recognition and Machine Learning》Christopher M. Bishop
    学习笔记-----《Pattern Recognition and Machine Learning》Christopher M. Bishop
    “数学之美”笔记
    win10下使用nodejs安装及webstorm创建express项目的指导
    deepin/ubuntu下搭建Jekyll环境
    struts2.3.23升级到struts2.3.32
    struts2.5能不能再恶心点
    线程通信、线程同步以及进城通信的真的搞懂了么
    WINFORM数据库操作,有点像安装里面的SQLITE
  • 原文地址:https://www.cnblogs.com/alternative/p/7463420.html
Copyright © 2011-2022 走看看