龙空技术网

java中继承和组合的运用以及初始化顺序

远方老表 113

前言:

现在小伙伴们对“java的组合与继承”大约比较注重,咱们都需要了解一些“java的组合与继承”的相关内容。那么小编同时在网上收集了一些对于“java的组合与继承””的相关知识,希望你们能喜欢,同学们一起来了解一下吧!

通过demo展现java中 包含继承和组合时,程序的初始化顺序.

1.初始化顺序

public class App2 {    public static void main(String[] args){        new Child1();    }}class Parent {    public Parent(){        System.out.println("-----parent constructor method");    }    static{        System.out.println("-----parent static block");    }    {        System.out.println("-----parent non static block");    }}class Child1 extends Parent{    private DependencyClass dependencyClass = new DependencyClass();    public Child1(){        System.out.println("*****child1 constructor method");    }    static{        System.out.println("*****child1 static block");    }    {        System.out.println("*****child1 non static block");    }    static{        System.out.println("*****child1 static block1");    }    {        System.out.println("*****child1 non static block1");    }}class DependencyClass{    DependencyClass(){        System.out.println("=====dependencyClass constructor method");    }    static{        System.out.println("=====dependencyClass static block");    }    {        System.out.println("=====dependencyClass non static block");    }}

输出:

-----parent static block

*****child1 static block

*****child1 static block1

-----parent non static block

-----parent constructor method

=====dependencyClass static block

=====dependencyClass non static block

=====dependencyClass constructor method

*****child1 non static block

*****child1 non static block1

*****child1 constructor method

从输出结果看:

父类的静态代码块->子类的静态代码块->父类的非静态代码块->父类的构造方法->成员初始化->子类的非静态代码块->子类的构造函数

还可以看出 静态代码块以及非静态代码块都是按声明顺序执行的

2.继承中的注意点

package javaBase1;public class App3 {    public static void main(String[] args){        new Child1();    }}class Parent{    public Parent(){        this.showName();    }    public void showName(){        System.out.println("parent method");    }}class Child1 extends Parent{    private String name = "张三";    public Child1(){        name = "李四";    }    @Override    public void showName(){        System.out.println("Child1 method " + name);    }}

输出:

Child1 method null

java中 this指向的是当前实例, new 的是Child1 初始化父类的时候 就会调用Child1的方法.

java编程思想中说: 一个动态绑定的方法调用会向外深入到继承层次结构内部.

但此时子类Child1还未初始化 成员属性还未赋值

step by step forward

标签: #java的组合与继承