Calling the overridden method from the constructor

In the following example:

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(); } } 
  • Why the conclusion, as shown below,
 Child Show 0 Child Show 20 
  • I thought that constructors can access instance instances only after its superconstructors have completed.

I think that what happens here is that the super constructor calls the show show () method because this method has been overridden in Child. how it was redefined, but why is the value x 0 and why can it access this method before the completion of the superconstructor?

+8
java constructor
source share
4 answers

I think what happens here is that the super constructor calls the child show () method because this method has been overridden in Child.

Correctly

but why is the value x 0

since it is not yet initialized (x of Child)

and why can he access this method before the completion of the superstructor?

That is why in the constructor you should never call a method that can be overridden (incomplete public and protected).

Edit:

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

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

+11
source share

You can call overridden methods from constructors, but Bad , but should not . You have illustrated the reason why this is bad: the derived class does not get the ability to initialize, so uninitialized fields will be used - in your example, the default value for int x is 0 , so it prints 0 .

+6
source share

A chain of designers makes sense to explain what it is. The first task of a subclass constructor method is to call its superclass constructor method. This ensures that the creation of the subclass object begins with the initialization of the overlying classes 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

+2
source share

Child overrides the redefinition of the show method because this is what the Java specification requires. Here's a great discussion on why you shouldn't do this . The value of x is zero because Child has not yet completed initialization.

+1
source share

All Articles