关于继承动态绑定验证代码--java自学笔记

 

在查看ArrayList.containsAll方法的源码时发现,ArrayList没有重写containsAll方法,向上查询后发现此方法在AbstractCollection类中有实现。这个AbstractCollection类是ArrayList的父类的父类。关系结构如下图。

在AbstractCollection中代码如下,这个类自己有实现contains方法。

    public boolean containsAll(Collection<?> c) {
        for (Object e : c)
            if (!contains(e))
                return false;
        return true;
    }

    同时,ArrayList中也重写了contains方法。由此产生一个疑问:在继承关系中,多态是一个什么情况。父类的引用调用子类对象的方法时,动态绑定是怎么样的。此处的contains是AbstractCollection的方法还是ArrayList的方法。所以特地写了代码验证。

通过以下代码可以得出结论,方法调用是动态绑定到对象。当对象类中有方法时用自己的方法,没有时向上查询。在父类中方法中调用了方法依然是从对象类中开始找,如果没有再层层向上找。

package com.syy.test;


/**
 * @author Songyy
 * @create 2018-08-04 星期六 16:04
 */
public class Demo_Inherit {
    public static void main(String[] args) {
        aFather p = new bSon();
        p.aMethod();


    }
}

class aFather{
    private int num;
    private int age;

    public int aMethod() {
        System.out.println("aFather aMethod");
        return num;
    }
    public int bMethod() {
        System.out.println("aFather bMethod");
        return num;
    }
    public int cMethod() {
        System.out.println("aFather cMethod");
        return num;
    }
    public int dMethod() {
        System.out.println("aFather dMethod");
        return num;
    }
}

class aSon extends aFather {
    @Override
    public int aMethod() {
        System.out.println("aSon aMethod");
        bMethod();
        cMethod();
        dMethod();
        return 123;
    }
    public int cMethod() {
        System.out.println("aSon cMethod");
        return 123;
    }

}

class bSon extends aSon {
    @Override
    public int bMethod() {
        System.out.println("bSon bMethod");
        return 324;
    }
}

运行结果。

aSon aMethod
bSon bMethod
aSon cMethod
aFather dMethod

Process finished with exit code 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值