Java Reference
In-Depth Information
System.out.println("Using SmartDog() constructor");
}
public SmartDog(String name, double price) {
// Initialize name and price to specified name and price
this.name = name;
this.price = price;
System.out.println("Using SmartDog(String, double) constructor");
}
/* Rest of code remains the same */
}
Note that you changed the code only inside the constructor that accepts no parameters. Instead of setting the
default values for
name
and
price
in the first constructor, you called the second constructor with the default values as
parameters from the first one.
Using a return Statement Inside a Constructor
A constructor cannot have a return type in its declaration. It means a constructor cannot return any value. Recall that
a
return
statement is of two types: one with a return expression and one without a return expression. The
return
statement without a return expression simply returns the control to the caller without returning any value. You
can use a
return
statement without a return expression inside a constructor body. When a
return
statement in a
constructor is executed, the control returns to the caller, ignoring the rest of the constructor's code.
The following code shows an example of using a
return
statement in a constructor. If the parameter
x
is a
negative number, the constructor simply executes a
return
statement to end the call to the constructor. Otherwise,
it performs some logic.
public class Test {
public Test(int x) {
if (x < 0) {
return;
}
/* Perform some logic here */
}
}
Access Level Modifier for a Constructor
Access level for a constructor determines the part of the program that can use that constructor in an object creation
expression to create an object of that class. You can specify one of the four access levels for a constructor:
public
,
private
,
protected
, and package-level. The following code declares four constructors for the
Test
class. A comment
for each constructor explains its access level.
// Class Test has public access level
public class Test {
// Constructor #1 - Package-level access
Test() {
}