static方法与覆盖

     The Java Programming Language中的一段话:Static members within a classwhether fields or methodscannot be overridden, they are always hidden. The fact that they are hidden has little effect, howevereach static field or method should always be accessed via the name of its declaring class, hence the fact that it gets hidden by a declaration in a subclass is of little consequence. If a reference is used to access a static member then, as with instance fields, static members are always accessed based on the declared type of the reference, not the type of the object referred to.

开始不是特别明白,看了Java Puzzlers中的一段话,理解的差不多了。

转载如下:

看看一个程序,动态绑定与静态绑定。

  1. classDog{
  2. publicstaticvoidbark(){
  3. System.out.print("woof");
  4. }
  5. }
  6. classBasenjiextendsDog{
  7. publicstaticvoidbark(){}
  8. }
  9. publicclassBark{
  10. publicstaticvoidmain(Stringargs[]){
  11. Dogwoofer=newDog();
  12. Dognipper=newBasenji();
  13. woofer.bark();
  14. nipper.bark();
  15. }
  16. }

 

啊,你可能一开始就认为这应该是动态绑定吧,多态性!!那么应该只打印一个woof吧!可并非如此,可怜的小狗Basenji也叫唤了(据书中所说,此种狗在非洲,而且从来不叫唤,无法想象这世上有不叫唤的狗,呵呵)。问题就在于bark是一个静态方法,而静态方法的调用不存在任何动态绑定机制!对于静态方法,只会根据调用者的编译期类型进行调用,woofer,nipper都被声明为Dog,他们的编译期类型相同。你可能要问,子类 Basenji中的bark()方法不是覆写了父类中的bark方法,那么是怎么回事?答案是它隐藏了父类中的bark方法,静态方法是不能被覆写的,他们只能被隐藏。要想使这只可怜的小狗回归不叫唤的“正常”状态,去掉方法之前的static标签即可。

注意隐藏的含义。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值