java继承实现的基本原理

 方法调用的过程

寻找要执行的实例方法的时候,是从对象的实际类型信息开始查找的,找不到的时候,再查找父类类型信息。

动态绑定,而动态绑定实现的机制就是根据对象的实际类型查找要执行的方法,子类型中找不到的时候再查找父类。

变量访问的过程

对变量的访问是静态绑定的,无论是类变量还是实例变量。代码中演示的是类变量:b.s和c.s,通过对象访问类变量,系统会转换为直接访问类变量Base.s和Child.s。

示例代码:

package com.xc.xcspringboot.chapter4.chapter4_3_1;

/**
 * Created by xc on 2019/10/6
 * 代码清单4-7 演示继承原理:Base类
 */
public class Base {

    /**
     * 静态变量s
     */
    public static int s;
    /**
     * 实例变量a
     */
    private int a;

    // 静态初始化代码块
    static {
        System.out.println("基类静态代码块, s: " + s);
        s = 1;
    }

    // 实例初始化代码块
    {
        System.out.println("基类实例代码块, a: " + a);
        a = 1;
    }

    /**
     * 构造方法
     */
    public Base() {
        System.out.println("基类构造方法, a: " + a);
        a = 2;
    }

    /**
     * 方法step
     */
    protected void step() {
        System.out.println("base s: " + s + ", a: " + a);
    }

    /**
     * 方法action
     */
    public void action() {
        System.out.println("start");
        step();
        System.out.println("end");
    }
}
package com.xc.xcspringboot.chapter4.chapter4_3_1;

/**
 * Created by xc on 2019/10/6
 * 代码清单4-8 演示继承原理:Child类
 */
public class Child extends Base {
    /**
     * 和基类同名的静态变量s
     */
    public static int s;
    /**
     * 和基类同名的实例变量a
     */
    private int a;

    static {
        System.out.println("子类静态代码块, s: " + s);
        s = 10;
    }

    {
        System.out.println("子类实例代码块, a: " + a);
        a = 10;
    }

    public Child() {
        System.out.println("子类构造方法, a: " + a);
        a = 20;
    }

    protected void step() {
        System.out.println("child s: " + s + ", a: " + a);
    }
}
package com.xc.xcspringboot.chapter4.chapter4_3_1;

/**
 * Created by xc on 2019/10/6
 */
public class Chapter4_3_1 {
    public static void main(String[] args) {
        System.out.println("---- new Child()");
        Child c = new Child();
        System.out.println("\n---- c.action()");
        c.action();
        Base b = c;
        System.out.println("\n---- b.action()");
        b.action();
        System.out.println("\n---- b.s: " + b.s);
        System.out.println("\n---- c.s: " + c.s);
    }
}
---- new Child()
基类静态代码块, s: 0
子类静态代码块, s: 0
基类实例代码块, a: 0
基类构造方法, a: 1
子类实例代码块, a: 0
子类构造方法, a: 10

---- c.action()
start
child s: 10, a: 20
end

---- b.action()
start
child s: 10, a: 20
end

---- b.s: 1

---- c.s: 10

猜你喜欢

转载自www.cnblogs.com/ooo0/p/11627013.html