Java Reference
In-Depth Information
Notice the default constructor does not do anything at all. However, it does allow us to
instantiate
Tomato
objects using
new
with empty parentheses:
Tomato roma = new Tomato();
Because the
Tomato
class does not contain any explicit initialization and the default
constructor does not do anything, the values of the fi elds will be their corresponding
default value, which is
0.0
for the
double
weight
and
false
for the
boolean
ripe
.
Know When a Class Gets a Default Constructor
Keep in mind that you only get a default constructor if you do not explicitly include one in
your class. Suppose we modify the
Tomato
class and explicitly declare a constructor:
public class Tomato extends Fruit {
public Tomato(double weight, boolean ripe) {
this.weight = weight;
this.ripe = ripe;
}
//The remainder of the class definition remains the same
}
Because this
Tomato
class has a constructor, the compiler does not add a default
constructor. With only one constructor, that means there is only one way to instantiate a
new
Tomato
, and that is by passing in a
double
and a
boolean
. For example:
Tomato beefsteak = new Tomato(10.45, false);
The following line of code will not compile with this
Tomato
class:
Tomato t = new Tomato(); //Generates a compiler error
Because knowing when a class gets a default constructor is a specifi c exam objective,
expect at least one question to test your knowledge of this topic.
Using
this
in Constructors
The
this
keyword in Java represents the reference that every object has to itself. The
this
keyword also has another use within constructors that is unrelated to the
this
reference.
You can use the
this
keyword to invoke another constructor in the same class, allowing
you to avoid repeating code in multiple constructors.
Search WWH ::
Custom Search