Java Reference
In-Depth Information
In MyClass , only the first constructor actually assigns a value to a and b . The second
constructor simply invokes the first. Therefore, when this statement executes:
the call to MyClass(8) causes this(8, 8) to be executed, which translates into a call to
MyClass(8, 8) .
Invoking overloaded constructors through this( ) can be useful because it can prevent
the unnecessary duplication of code. However, you need to be careful. Constructors that
call this( ) will execute a bit slower than those that contain all of their initialization code
in-line. This is because the call and return mechanism used when the second constructor is
invoked adds overhead. Remember that object creation affects all users of your class. If
your class will be used to create large numbers of objects, then you must carefully balance
the benefits of smaller code against the increased time it takes to create an object. As you
gain more experience with Java, you will find these types of decisions easier to make.
There are two restrictions you need to keep in mind when using this( ) . First, you can-
not use any instance variable of the constructor's class in a call to this( ) . Second, you
cannot use super( ) and this( ) in the same constructor because each must be the first
statement in the constructor.
Search WWH ::




Custom Search