父子类初始化顺序及方法调用

来源:互联网 发布:已备案过期域名查询 编辑:程序博客网 时间:2024/05/22 17:13

记个笔记吧~

父类静态代码块>子类静态代码块>父类非静态代码块>父类构造函数>子类非静态代码块>子类构造函数

public class Parent {     public Parent(){            System.out.println("parent constructor method");            staticHH();        }        static{            System.out.println("parent static code");        }        //非静态代码块        {            System.out.println("parent nonStatic code");        }        public static void staticHH(){            System.out.println("parent static hh");        }        public void hh(){            System.out.println("parent hh");        }}
public class Children extends Parent{    public Children(){        System.out.println("children constructor code");        staticHH();    }    static{        System.out.println("children static code");    }    //非静态代码块    {        System.out.println("children nonStatic code");    }    public static void staticHH(){        System.out.println("children static hh");    }    public void hh(){        System.out.println("children hh");    }    public static void main(String[] args){        Children c = new Children();        /* Parent pc=new Children();        Parent pp=new Parent();        pc.hh();        pp.hh();*/    }}

这里写图片描述

调用父子类同名方法时,根据初始化方法来决定具体父类还是子类的方法 ,而不是由声明决定

public static void main(String[] args){        //Children c = new Children();        Parent pc=new Children();        Parent pp=new Parent();        pc.hh();        pp.hh();    }

这里写图片描述

阅读全文
1 0