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
复制代码

 

posted @   草木物语  阅读(2045)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示