Calling an overridden method from a constructor

后端 未结 4 938
滥情空心
滥情空心 2021-02-15 09:22

In the following example:

class Base {    
    int  x=10;  

    Base() {    
      show();
    }  

    void show() {   
        System.out.print (\"Base Show \         


        
相关标签:
4条回答
  • 2021-02-15 10:02

    You can call overriden methods from constructors, but it's bad and you shouldn't. You illustrated the reason why this is bad: the derived class doesn't get a chance to get initialized, so uninitialized fields will be used - in your example, the default for int x is 0, that's why it's printing 0.

    0 讨论(0)
  • 2021-02-15 10:03

    Childs override of the show method is invoked because that's what the Java spec calls for. Here is a great discussion of why you should not do it. The value of x is zero because Child has not finished initializing yet.

    0 讨论(0)
  • 2021-02-15 10:15

    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.

    That is correct

    but why is the value of x 0

    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).

    Edit:

    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).

    0 讨论(0)
  • 2021-02-15 10:23

    constructor chaining it makes sense to explain exactly what that is. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.

    http://java.about.com/b/2009/02/07/java-term-of-the-week-constructor-chaining.htm

    http://javahours.blogspot.com/2008/12/constructor-chain.html

    0 讨论(0)
提交回复
热议问题