Defining Constructors
Explore the purpose and structure of Java constructors in this lesson. Understand how default and parameterized constructors initialize an object's instance variables, and how constructors facilitate memory allocation and data setup when creating new objects in Java classes.
We'll cover the following...
The default constructor
The definition of any constructor begins with the access modifier public, the name of the class—which is the name of the constructor—and a pair of parentheses. Nothing appears between these parentheses for a default constructor. For example, the definition of the default constructor for the class Greeter is
/** Creates a default Greeter object. */
public Greeter()
{
greeting = "Hello, world!";
} // End default constructor
Let’s recall how we used the class Greeter in the first lesson of this chapter:
We see that the statement
Greeter standardWelcomer = new Greeter();
creates a Greeter object and invokes the default constructor. Memory space is allocated for the new object, including space for a string called greeting. This memory allocation happens without any effort on our part. Thus, the new object has its own data field, or instance variable, greeting, that is a string, as shown in ...