- A constructor call starts with Java's
new
keyword:
new
BagOfCheese()
and
- A constructor call's name is the name of a Java class:
new <strong>BagOfCheese</strong>()
package com.allmycode.a09_05;
public class BagOfCheese {
public String kind;
public double weight;
public int daysAged;
public boolean isDomestic;
<strong> public BagOfCheese() {</strong>
<strong> }</strong>
}
The boldface code
<strong>public BagOfCheese() {</strong>
<strong>}</strong>
is a very simple constructor declaration. This declaration (unlike most constructor declarations) has no statements inside its body. This declaration is simply a header (BagOfCheese()
) and an empty body ({}
).
You can type the code exactly as it is. Alternatively, you can omit the code in boldface type, and Java creates that constructor for you automatically. (You don't see the constructor declaration in the Android Studio editor, but Java behaves as if the constructor declaration exists.)
A constructor's declaration looks much like a method declaration. But a constructor's declaration differs from a method declaration in two ways:
- A constructor's name is the same as the name of the class whose objects the constructor constructs.
The class name is BagOfCheese
, and the constructor's header starts with the name BagOfCheese
.
- Before the constructor's name, the constructor's header has no type.
Unlike a method header, the constructor's header doesn't say int BagOfCheese()
or even void BagOfCheese()
. The header simply says BagOfCheese()
.
BagOfCheese
object.