Java Programming for Android Developers For Dummies
Book image
Explore Book Buy On Amazon
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 <strong>BagOfCheese</strong>()

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;

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

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.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a professor in the Department of Mathematics and Computer Science at Drew University in Madison, New Jersey. He has lectured at conferences in the United States, Europe, Australia, and Asia. He hosts podcasts and videos about software and other technology topics. He is the author of many articles and books, including Java For Dummies.

This article can be found in the category: