从构造函数调用重写的方法 [英] Calling an overridden method from a constructor

查看:57
本文介绍了从构造函数调用重写的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中:

class Base {    
    int  x=10;  

    Base() {    
      show();
    }  

    void show() {   
        System.out.print ("Base Show " +x + "  ");
    }  
}  

class Child extends Base {   
    int x=20;  

    Child() {
        show();
    }  

    void show() {    
        System.out.print("Child Show " + x +"  ") ; 
    }  

    public static void main( String s[ ] ) {   
        Base obj = new Child();   
    }  
} 

  • 为什么输出如下所示
  • Child Show 0  Child Show 20
    

    • 我认为构造函数只能在其超级构造函数完成后才能访问实例成员.
    • 我认为这里发生的是,超级构造函数正在调用子级的show()方法,因为该方法在Child中被覆盖.因为它已被覆盖,但为什么x 0的值为何,为什么它可以在超级构造函数完成之前访问此方法?

      I think what is happening here is that the super constructor is calling the child's show() method because this method was overridden in Child. as it has been overridden but why is the value of x 0 and why is it able to access this method before the super constructor has completed?

      推荐答案

      我认为这里发生的是,超级构造函数正在调用子级的show()方法,因为该方法在Child中被覆盖.

      I think what is happening here is that the super constructor is calling the child's show() method because this method was overriden in Child.

      是的

      但是为什么x 0的值

      but why is the value of x 0

      因为尚未初始化(孩子的x)

      because it's not initialized yet (x of Child)

      为什么在超级构造函数完成之前它能够访问此方法?

      and why is it able to access this method before the super constructor has completed?

      这就是为什么在构造函数中永远不要调用可以被覆盖的方法(非最终公共方法和受保护方法)的原因.

      That's exactly why in a constructor you should never call a method, which can be overridden (non-final public and protected).

      这里奇怪的是,所有内容都具有默认/程序包专用可见性.这可能会产生一些奇怪的影响.参见: http://www.cooljeff.co.uk/2009/05/03/the-subtleties-of-overriding-package-private-methods/

      The strange thing here is that everything has default/ package-private visibility. This can have some strange effects. See: http://www.cooljeff.co.uk/2009/05/03/the-subtleties-of-overriding-package-private-methods/

      我建议尽可能避免使用具有默认可见性的替代方法(您可以通过将其声明为最终形式来避免这种情况.)

      I recommend to avoid overriding methods with default visibility if possible (you can prevent this by declaring them final).

      这篇关于从构造函数调用重写的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆