Java Reference
In-Depth Information
public class Test {
Test() {
int k = 10; // First statement
this(k); // Second statement. A compile-time error
}
Test(int x) {
}
}
An attempt to compile the code for the above Test class will generate the following error
message:
Error(4): call to this must be first statement in constructor
A constructor cannot call itself because it will result in a recursive call. In the following code
for the Test class, both constructors attempt to call themselves:
public class Test {
Test() {
this();
}
Test(int x ) {
this(10);
}
}
An attempt to compile the above code will result in the following error. One error message is
generated for each attempt to call the constructor itself.
Error(2): recursive constructor invocation
Error(6): recursive constructor invocation
Typically, you create overloaded constructors for a class when you have many ways to initialize an object of a
class. Let's consider the SmartDog class shown in Listing 6-30. Two constructors give you two ways to initialize a new
SmartDog object. The first one initializes the name and the price with default values. The second constructor lets you
initialize name and price with the value supplied by the caller. Sometimes you may perform some logic to initialize the
object inside a constructor. Letting you call another constructor from a constructor allows you to write such logic only
once. You can make use of this feature for your SmartDog class, as shown:
// SmartDog.java
package com.jdojo.cls;
public class SmartDog {
private String name;
private double price;
public SmartDog() {
// Call another constructor with "Unknown" and 0.0 as parameters
this("Unknown", 0.0);
 
Search WWH ::




Custom Search