浅谈Java方法调用的优先级问题
实现Java多态性的时候,关于方法调用的优先级:
我们这样假设下,super(超类)、this(当前类对象)、show(方法)、object(对象),方法调用优先顺序:①this.show(object)>②super.show(object)>③this.show((super)object)>④super.show((super)object)
先看以下代码
classParentCls{ publicStringshow(ChildAobj){ return"ParentandChildA"; } publicStringshow(ParentClsobj){ return"Parent"; } }
然后写一个子类ChildA,继承ParentCls:
classChildAextendsParentCls{ publicStringshow(ChildAobj){ return"ChildA"; }; publicStringshow(ParentClsobj){ return"ChildAandParent"; }; }
写一个子类ChildB,继承ChildA:
classChildBextendsChildA{
}
测试下
publicstaticvoidmain(String[]args){ ParentClsp1=newParentCls(); ParentClsp2=newChildA(); ChildAa=newChildA(); ChildBb=newChildB(); System.out.println(p1.show(a)); System.out.println(b.show(a)); System.out.println(a.show(b)); System.out.println(p2.show(a)); }
输出
ParentandChildA ChildA ChildA ChildA
第一个输出,p1是ParentCls的实例,且类ParentCls中有show(ChildAobj)方法,直接执行该方法,①有效;
第二个输出,b是ChildB的实例,类ChildB中没有show(ChildAobj)方法,①无效,再从ChildB的父类ChildA查找,ChildA中刚好有show(ChildAobj)方法,②有效;
第三个输出,a是ChildA的实例,b是ChildB的实例,类ChildA中没有show(ChildBobj)方法,①无效,再从ChildA的父类ParentCls入手,ParentCls中也没有show(ChildBobj)方法,②无效,从ChildB的父类入手,(super)ChildB即是ChildA,所以a.show(b)=>a.show(a),ChildA中刚好有show(ChildAobj)方法,③有效;
④就不作演示,根据①②③很容易得出结论;
第四个输出,体现Java多态性,符合①,但是p2是引用类ChildA的一个对象,ChildA重写覆盖了ParentCls的show()方法,所以执行ChildA的show()方法;
补充知识:Java中关于静态块,初始化快,构造函数的执行顺序
代码如下:
publicclassParentDemo{ static{ System.out.println("thisisParentDemostatic"); } { System.out.println("thisisParentDemocodeblock"); } publicParentDemo(){ System.out.println("thisisParentDemoconstructor"); } } publicclassSonDemoextendsParentDemo{ static{ System.out.println("thisisSonDemostatic"); } { System.out.println("thisisSonDemocodeblock"); } publicSonDemo(){ System.out.println("thisisSonDemoconstructor"); } } publicclassTestMain{ publicstaticvoidmain(String[]args){ newSonDemo(); } }
输出结果:
thisisParentDemostatic thisisSonDemostatic thisisParentDemocodeblock thisisParentDemoconstructor thisisSonDemocodeblock thisisSonDemoconstructor
由上可见,Java中静态块中的代码在类加载时执行,子类继承父类。会按照继承的顺序先执行静态代码块。当实例化对象的时候,同理会按照继承的顺序依次执行如下代码:
代码块,构造函数,当父类的执行完以后,再执行子类。
以上这篇浅谈Java方法调用的优先级问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。