15.16 CONSTRUCTOR ORDER DEPENDENCIES IN JAVA


15.16 CONSTRUCTOR ORDER DEPENDENCIES IN JAVA

The order in which constructors are invoked and the data members initialized for a derived-class object in Java is given by the following:

  1. Invoke the constructor of the derived class by appropriating the required amount of memory and set all the data members in this memory to their default values (zero for all numeric types, false for boolean, ‘\uOOOO’ for char, and null for object reference).

  2. Invoke the base-class constructor.

  3. Execute the initialization code attached to any of the data members in the base class and initialize those data members accordingly.

  4. Execute the code in the body of the base-class constructor. This base-class constructor could be a no-arg constructor.

  5. Execute the initialization code attached to any of the data members of the derived class and initialize those data members accordingly.

  6. Execute the code in the body of the derived-class constructor.

Paralleling our C++ discussion of Section 15.11, now consider classes Base and Derived as shown below, each with its own version of a method named foo() this method being invoked in only the base-class constructor. The question is whether the base-class constructor will invoke the base-class foo() or the derived-class foo() when we construct an object of type Derived. We saw that for the C++ case, it was the base-class foo() However, as can be seen from the example shown below, for the Java case it is the derived-class foo() that is invoked.

 
//ConstructorOrderFoo.java class Base { public void foo() { System.out.println( "Base's foo invoked"); } public Base() { foo(); } } class Derived extends Base { public void foo(){ System.out.println("Derived's foo invoked"); } public Derived() {} } class Test { public static void main(String [] args) { Derived d = new Derived(); //Derived's foo() invoked } }

What this example teaches us is that one should be careful with using overridable methods in constructors. Any method that is neither private, nor static, nor final is overridable.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net