Calling a Java Constructor in Your Android App - dummies

By Barry A. Burd

You can use a Java constructor call in your Android app. A constructor call creates a new object from an existing class. You can spot a constructor call by noticing that

  • 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 BagOfCheese()

When Java encounters a method call, Java executes the statements inside a method’s declaration. Similarly, when Java encounters a constructor call, Java executes the statements inside the constructor’s declaration. When you create a new class, Java can create a constructor declaration automatically. If you want, you can type the declaration’s code manually. This code shows you what the declaration’s code would look like:

package com.allmycode.a09_05;

public class BagOfCheese {

public String kind;

public double weight;

public int daysAged;

public boolean isDomestic;

public BagOfCheese() {

}

}

The boldface code

public BagOfCheese() {

}

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().

The constructor declaration contains no statements. That isn’t typical of a constructor, but it’s what you get in the constructor that Java creates automatically. With or without statements, calling the constructor creates a brand-new BagOfCheese object.