Java 超类引用子类对象的示例代码

动态方法分配 dynamic method dispatch
一个被重写的方法的调用会在运行时解析,而不是编译时解析
Java 会根据在调用发生时引用的对象的类型来判断所要执行的方法

public class DynamicMethodDispatch {
    void callSubClassMethod(subDynamicMethodDispatch d) {
        System.out.println("Call from SuperClass");
        d.subClassMethod();
        System.out.println("END CALL");
    }
    
    public static void main(String[] args) {
        DynamicMethodDispatch dispatch = new DynamicMethodDispatch();
        dispatch.callSubClassMethod(new subDynamicMethodDispatch());
        
        dispatch = new subDynamicMethodDispatch();
        dispatch.callSubClassMethod(dispatch);
    }
}

class subDynamicMethodDispatch extends DynamicMethodDispatch {
    void subClassMethod() {
        System.out.println("Method from subclass.");
    }
}

转载于:https://www.cnblogs.com/gebilaowangpython/p/10409382.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值