11.2 CAN MULTIPLE CONSTRUCTORS HELP EACH OTHER?


11.2 CAN MULTIPLE CONSTRUCTORS HELP EACH OTHER?

When multiple constructors are defined for a class, can they help each other during the construction of an object of the class? The answer to this is yes in Java and no in ISO compatible C++.

In Java it is permissible for one constructor to call another constructor defined for the same class through the function this(). Here is an example:

 
//MultiConstructors.java class X { private int x; private int y; public X(){ x = 5; } //(A) public X(int m) { //(B) this(); //(C) y = m; } public static void main( String[] args ) { X xobj = new X( 100 ); System.out.println ( xobj.x + " " + xobj.y ); // 5 100 } }

We have two constructors for this class, in lines (A) and (B). The constructor of line (B) invokes the constructor of line (A) in line (C) by using the function call this (). In Java, the special function call

     this(.......) 

can always be used to invoke any constructor inside any other constructor for the same class. The standard overload resolution, presented in Chapter 9, is used to decide which constructor to invoke in response to this(). So, evidently, the arguments supplied to this() play a principal role in determining which specific constructor is selected. When a constructor invokes another constructor in this manner, the statement this(.) must be the first executable statement. This is referred to as explicit constructor invocation in Java.




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