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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM